从轮廓opencv中的多个框中查找矩形框
Find rectangle box from multiple box in contours opencv
我有一个问题,关于如何在等高线 opencv 中的这些小矩形中找到最大的矩形,请帮助我
这是 cv2.findContours() 中的小矩形
我得到了轮廓列表。我绘制它,我得到了这个
我想要黄色的矩形框
这是代码
img_grey = cv2.cvtColor(bg_img,cv2.COLOR_BGR2GRAY)
ret,thresh_img = cv2.threshold(img_grey, 100, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
有没有办法找到大矩形(黄色)
谢谢
找到等高线后,您需要从离开的地方继续。
方法:
- 初始化数组
- 遍历每个轮廓并将其点存储在数组中
- 求两个轴的最大值和最小值(
numpy
是你的朋友!)
- 用它们画一个矩形。
代码:
# create copy of original color image
img2 = bg_img.copy()
# Initialize array with value (0,0)
cc = np.array([[0, 0]], dtype=int)
# Iterate through each contour
for i, c in enumerate(contours):
# reshape from (L, 1, 2) to (L, 2), where L is a tuple of (x, y)
c_modified = c.reshape(len(contours[i]), 2)
# concatenate to initial array
cc = np.concatenate((cc, c_modified), axis = 0)
# remove the first element of initialized array
new_cc = cc[1:]
# obtain max and min value along Y-axis
y2 = np.max(new_cc[:,1])
y1 = np.min(new_cc[:,1])
# obtain max and min value along X-axis
x2 = np.max(new_cc[:,0])
x1 = np.min(new_cc[:,0])
# Draw rectangle using those points on copy of the image
img2 = cv2.rectangle(img2, (x1, y1), (x2, y2), (255,255, 0, 3)
结果:
我有一个问题,关于如何在等高线 opencv 中的这些小矩形中找到最大的矩形,请帮助我
这是 cv2.findContours() 中的小矩形
我得到了轮廓列表。我绘制它,我得到了这个
我想要黄色的矩形框
这是代码
img_grey = cv2.cvtColor(bg_img,cv2.COLOR_BGR2GRAY)
ret,thresh_img = cv2.threshold(img_grey, 100, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
有没有办法找到大矩形(黄色) 谢谢
找到等高线后,您需要从离开的地方继续。
方法:
- 初始化数组
- 遍历每个轮廓并将其点存储在数组中
- 求两个轴的最大值和最小值(
numpy
是你的朋友!) - 用它们画一个矩形。
代码:
# create copy of original color image
img2 = bg_img.copy()
# Initialize array with value (0,0)
cc = np.array([[0, 0]], dtype=int)
# Iterate through each contour
for i, c in enumerate(contours):
# reshape from (L, 1, 2) to (L, 2), where L is a tuple of (x, y)
c_modified = c.reshape(len(contours[i]), 2)
# concatenate to initial array
cc = np.concatenate((cc, c_modified), axis = 0)
# remove the first element of initialized array
new_cc = cc[1:]
# obtain max and min value along Y-axis
y2 = np.max(new_cc[:,1])
y1 = np.min(new_cc[:,1])
# obtain max and min value along X-axis
x2 = np.max(new_cc[:,0])
x1 = np.min(new_cc[:,0])
# Draw rectangle using those points on copy of the image
img2 = cv2.rectangle(img2, (x1, y1), (x2, y2), (255,255, 0, 3)
结果: