目錄
一?實現方法
二 涉及的OpenCV函數
三 代碼
四 效果圖
一?實現方法
①利用OTSU方法將前景與背景分割。
②使用連通區域分析可以將具有相同像素值且位置相鄰的前景像素點組成的圖像區域識別。
③畫bbox。
④顯示結果。
二 涉及的OpenCV函數
① OpenCV提供了cv2.threshold()用于實現閾值處理。
ret, dst = cv2.threshold(src, thresh, maxval, type)
ret:代表返回的閾值。
src:原圖。
dst: 輸出圖。
thresh:要設定的閾值。
maxval: 當像素值超過了閾值或者小于閾值所賦予的值。
type:二值化操作的類型,包含5種類型。
② OpenCV提供了cv2.connectedComponentsWithStats()函數用于處理不規則連通區域。
retval, labels, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=8)
image : 是要處理的圖片,8位單通道的圖像。
connectivity : 可以選擇是4連通還是8連通。
retval : 返回值是連通區域的數量。
labels :一個輸入圖像大小的矩陣,其中每個元素的值等于其標簽。
stats :包含5個參數分別為x,y,h,w,s。分別對應每一個連通區域的外接矩形的起始坐標x,y;外接矩形的wide,height;s是labels對應的連通區域的像素個數。
centroids : 返回的是連通區域的質心。
三 代碼
import cv2
import matplotlib.pyplot as plt
def dealImg(img):b, g, r = cv2.split(img)img_rgb = cv2.merge([r, g, b])return img_rgb
def dealImageResult(img_path):img = cv2.imread(img_path)img_box = img.copy()gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# OTSU方法實現前景與背景分割ret2, dst_OTSU = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)# 識別出目標區域并用bbox框起來# 連通區域分析可以將具有相同像素值且位置相鄰的前景像素點組成的圖像區域識別ret, labels, stats, centroid = cv2.connectedComponentsWithStats(dst_OTSU)Iarea = sorted(stats, key=lambda s: s[-1], reverse=False)[-2]cv2.rectangle(img_box,(Iarea[0], Iarea[1]),(Iarea[0] + Iarea[2], Iarea[1] + Iarea[3]),(255, 0, 0),3)fig = plt.figure(figsize=(8, 8))titles = ["img", "gray", "OTSU", "img_box"]img = dealImg(img)img_box = dealImg(img_box)images = [img, gray, dst_OTSU, img_box]for i in range(4):plt.subplot(2, 2, i + 1), plt.imshow(images[i], 'gray')plt.title(titles[i])plt.xticks([]), plt.yticks([])plt.show()fig.savefig('test_results.jpg', bbox_inches='tight')
if __name__ == '__main__':dealImageResult("3.jpg")pass
四 效果圖
?
前文回顧
?入門篇目錄
?數字圖像處理(入門篇)一 圖像的數字化與表示
?數字圖像處理(入門篇)二 顏色空間
?數字圖像處理(入門篇)三 灰度化
?數字圖像處理(入門篇)四 像素關系
?數字圖像處理(入門篇)五 圖像數據預處理之顏色空間轉換
?數字圖像處理(入門篇)六 圖像數據預處理之坐標變化
?數字圖像處理(入門篇)七 圖像數據預處理之灰度變化
?數字圖像處理(入門篇)八 圖像數據預處理之直方圖
?數字圖像處理(入門篇)九 圖像數據預處理之濾波
?數字圖像處理(入門篇)十 邊緣檢測
?數字圖像處理(入門篇)十一 形態學處理
?數字圖像處理(入門篇)十二 自適應閾值分割
?數字圖像處理(入門篇)十三 仿射變換
?數字圖像處理(入門篇)十四 透視變換