我试图找到鱼后面的green rectangle的中心点,但我的方法不起作用。这是我的代码:
#Finding contours (almost always finds those 2 retangles + some noise):
_, conts, hierarchy = cv2.findContours(img_green, cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE)
for cnt in conts:
area = cv2.contourArea(cnt)
#filter noise
if area > 25:
M = cv2.moments(cnt)
x1, y1, w, h = cv2.boundingRect(cnt)
x2 = x1 + w # (x1, y1) = top-left vertex
y2 = y1 + h # (x2, y2) = bottom-right vertex
cy = int(M['m01']/M['m00']) # (cx, cy) = rect center
cx = int(M['m10']/M['m00'])
rect = cv2.rectangle(green_bar_win, (x1, y1), (x2, y2), (255,0,0), 2)
center = cv2.circle(green_bar_win, (cx, cy), 2, (0,0,255), 4)
正如您所看到的,它找到了矩形的轮廓,但是在鱼的位置处分开,形成了2种不同的形状。它也找到了这2个形状的中心(蓝点),但我不知道如何找到大的中间。我想到了所有找到的矩形中心的平均值,但我不知道怎么写这个。我通过hsv颜色找到矩形。帮助
编辑:我有' y1'从顶部矩形开始,但不知道如何在for循环中从底部获取y2。我试过这个:_, conts, hierarchy = cv2.findContours(img_green, cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE)
for cnt in conts:
area = cv2.contourArea(cnt)
#filter noise
if area > 25:
x1, y1, w, h = cv2.boundingRect(cnt)
x2 = x1 + w # (x1, y1) = top-left vertex
try:
rect_center = np.average([y1, y2])
except:
print("Failed to average")
y2 = y1 + h # (x2, y2) = bottom-right vertex
rect = cv2.rectangle(green_bar_win, (x1, y1), (x2, y2), (255,0,0), 2)
但它仍然失败,因为y2在分配之前使用。那么,在y1被' for'覆盖之前,我怎样才能从第二个循环中获得y2。循环?
答案 0 :(得分:1)
现在是时候把它打破到完整的答案。
识别每个矩形后,将其角点与每个现有形状进行比较。如果它具有相同的颜色和一对共同的角(共享边),则更新旧的矩形:用新矩形的其他角替换这两个角。
在代码中添加一些内容:
找到每个形状时,与已找到的形状进行比较。
rect_list = []
对于cnt in conts: area = cv2.contourArea(cnt)
#filter noise
if area > 25:
M = cv2.moments(cnt)
# ... several lines deleted
rect = cv2.rectangle(green_bar_win, (x1, y1), (x2, y2), (255,0,0), 2)
center = cv2.circle(green_bar_win, (cx, cy), 2, (0,0,255), 4)
# Look for adjacent shapes here
for old_rect in rect_list:
# fetch the corners of old_rect
# if old_rect has a pair of corners in common with
# the current rect, then merge the two.
# Do this by expanding the corners of old_rect.
else:
rect_list.append(rect)