嗨,我有一个代码,发现并绘制轮廓周围的对象是黄色.
下面是代码:
import cv2
import numpy as np
from PIL import ImageGrab
lower_yellow = np.array([20, 100, 100])
upper_yellow = np.array([30, 255, 255])
def test():
while True:
imgDef = ImageGrab.grab()
image = np.array(imgDef)
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
hsv = cv2.cvtColor(rgb, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
kernel = np.ones((5,5),np.uint8)
mask = cv2.dilate(mask, kernel, iterations=1)
mask = cv2.erode(mask, kernel, iterations=1)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image, contours, -1, (0,255,0), 3)
cv2.imshow('test', image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
if __name__ == "__main__":
test()
现在的输出如下所示:
我希望将彼此非常接近的等值线分组,并在它们周围绘制一个边界框,如下所示:
我怎样才能做到这一点呢?我是否应该研究scikitKMeans函数来对它们进行分组?
1条答案
按热度按时间qxsslcnc1#
你可以使用cv2.kmeans来实现这个目标。我建议把
cv2.RETR_EXTERNAL
改为cv2.RETR_TREE
。我在这里分享一个可能的解决方案,唯一的问题是你需要在使用cv2.kmeans之前知道集群的编号。get_contours_by_zones()
函数使用cv2.kmeans将每个等值线分配给一个组。