我有一個關于如何在輪廓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)
有沒有辦法找到大矩形(黃色)謝謝
uj5u.com熱心網友回復:
找到輪廓后,您需要從離開的地方繼續。
方法:
- 初始化一個陣列
- 遍歷每個輪廓并將其點存盤在陣列中
- 在兩個軸上找到最大值和最小值(
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)
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484523.html
標籤:opencv
下一篇:維納濾波器輸出看起來不夠好
