python& OpenCV:第二大对象 [英] Python & OpenCV: Second largest object
问题描述
我正在开发一个python脚本,以隔离图像中颜色匹配的最大和第二大对象.我设法得到最大的物体,在其周围绘制轮廓并绘制一个盒子.但是,我很想找到一个解决方案以找到第二大对象.我希望单独检测第二大物体.
I'm developing a python script to take isolate the largest and second largest objects that are matched by color in the image. I've managed to get the largest object, draw a contour around it and draw a box. However, I'm stumped to find a solution to find the second largest object. I want the second largest object to be detected separately.
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)
I'm using the following image for testing purposes: Image of balls
感谢您的帮助!
推荐答案
首先,首先创建轮廓和轮廓区域的数组,然后找到第n个最大轮廓,会更简单.
First of all, it's simpler to first create the array of contours and contour areas, then find the n'th largest contour.
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版本崩溃.
This should basically do what you want. I stripped the code of unnecessary stuff that caused crashes on my version of opencv.
这篇关于python& OpenCV:第二大对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!