讓我們以一個簡單的場景為例,,在該場景中我們有一個檸檬圖像,我們想要對其中的檸檬進行分割和計數(shù),。 圖像分割算法有分水嶺算法,、斑點計數(shù)算法、霍夫圓/橢圓算法,、輪廓檢測算法等,。在本文中,我使用了輪廓檢測和分水嶺算法,。 涉及的步驟:
首先,我們導(dǎo)入一些常見的Python依賴項,。 from __future__ import print_functionimport numpy as npimport cv2import matplotlib.pyplot as plt%matplotlib inlinefrom skimage import iofrom skimage.morphology import watershedfrom skimage.feature import peak_local_maxfrom scipy import ndimage 我們創(chuàng)建一個Python函數(shù)以可視化圖像,。Python代碼如下:
現(xiàn)在,我們讀取圖像,。 #loadfp = 'lemons1.jpg'img = cv2.imread(fp)show(img)print(img.shape) 現(xiàn)在,,我們對圖像進行預(yù)處理。步驟包括:
現(xiàn)在我們使用輪廓檢測,在我們“模糊”的圖像中找到檸檬,。為了去除小的和無關(guān)緊要的輪廓,,我們只選擇那些面積大于2000的輪廓(任意值,是超參數(shù)),。 contours, hierarchy = cv2.findContours(blur,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)copy2 = img.copy()count = []for x in contours: area = cv2.contourArea(x) if area > 2000 : count.append(x)cv2.drawContours(copy2, count, -1, (255,0,0), 3)show(copy2)print('number of lemons found via contour detection = ', len(count)) 現(xiàn)在我們使用分水嶺算法來分離相互接觸的檸檬(如果有的話),。
最后我們?nèi)煞N方法的平均值并打印結(jié)果。 ans = int((len(count) + len(np.unique(labels)) -1) / 2)print('number of lemon segments detected = ', ans)show(copy2) |
|
來自: taotao_2016 > 《圖像處理》