2014-08-28 80 views
2

我正在開發一個python腳本,以隔離圖像中顏色匹配的最大和次大對象。我已經設法得到最大的物體,圍繞它畫一個輪廓並畫一個盒子。然而,我很難找到找到第二大對象的解決方案。我想要分開檢測第二大物體。Python&OpenCV:第二大對象

import numpy as np 
import cv2 

font = cv2.FONT_HERSHEY_SIMPLEX 
lineType = cv2.LINE_AA 

im = cv2.imread('Photos/test.jpg') 
im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) 

ball_ycrcb_mint = np.array([0, 90, 100],np.uint8) 
ball_ycrcb_maxt = np.array([25, 255, 255],np.uint8) 
ball_ycrcb = cv2.inRange(im_ycrcb, ball_ycrcb_mint, ball_ycrcb_maxt) 
#cv2.imwrite('Photos/output2.jpg', ball_ycrcb) # Second image 
areaArray = [] 
count = 1 

_, contours, _ = cv2.findContours(ball_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 
for i, c in enumerate(contours): 
    area = cv2.contourArea(c) 
    areaArray.append(area) 
    areaLargest = np.argmax(areaArray) 
    areaLargestMax = max(areaArray) 
    areaLargestCnt = contours[areaLargest] 
    x, y, w, h = cv2.boundingRect(areaLargestCnt) 
    if area == areaLargestMax and area > 10000: 
     cv2.drawContours(im, contours, i, (255, 0, 0), 2) 
     cv2.rectangle(im, (x, y), (x+w, y+h), (0,255,0), 2) 
cv2.imwrite('Photos/output3.jpg', im) 

我用下面的圖像用於測試目的:Image of balls

任何幫助表示讚賞!

回答

2

首先,首先創建輪廓和輪廓區域的陣列,然後找到第n個最大輪廓更簡單。

import numpy as np 
import cv2 
im = cv2.imread('Photos/test.jpg') 
im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) 

ball_ycrcb_mint = np.array([0, 90, 100],np.uint8) 
ball_ycrcb_maxt = np.array([25, 255, 255],np.uint8) 
ball_ycrcb = cv2.inRange(im_ycrcb, ball_ycrcb_mint, ball_ycrcb_maxt) 
#cv2.imwrite('Photos/output2.jpg', ball_ycrcb) # Second image 
areaArray = [] 
count = 1 

contours, _ = cv2.findContours(ball_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 
for i, c in enumerate(contours): 
    area = cv2.contourArea(c) 
    areaArray.append(area) 

#first sort the array by area 
sorteddata = sorted(zip(areaArray, contours), key=lambda x: x[0], reverse=True) 

#find the nth largest contour [n-1][1], in this case 2 
secondlargestcontour = sorteddata[1][1] 

#draw it 
x, y, w, h = cv2.boundingRect(secondlargestcontour) 
cv2.drawContours(im, secondlargestcontour, -1, (255, 0, 0), 2) 
cv2.rectangle(im, (x, y), (x+w, y+h), (0,255,0), 2) 
cv2.imwrite('Photos/output3.jpg', im) 

這應該基本上做你想要的。我剝離了導致我的opencv版本崩潰的不必要的代碼。

+0

謝謝!有效。 – ahmadux 2014-08-29 15:01:42

5

你可以使用sorted(contours, key=cv2.contourArea, reverse=True)給你一個按地區降序的輪廓列表。

+0

這是一個好主意。從來沒有想過它! – 2017-01-28 17:00:23