我不想突出顯示與其他框部分重疊或不與任何其他框重疊的邊界框。我試圖通過檢測輪廓來做到這一點:
import cv2
# Read input image
img = cv2.imread('image.png')
# Convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply threshold
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)
# Find contours and hierarchy
cnts, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2:]
# Draw all contours with green color for testing
cv2.drawContours(img, cnts, -1, (0, 255, 0))
# Hierarchy Representation in OpenCV
# So each contour has its own information regarding what hierarchy it is,
# who is its child, who is its parent etc.
# OpenCV represents it as an array of four values : [Next, Previous, First_Child, Parent]
# Iterate contours and hierarchy:
for c, h in zip(cnts, hier[0]):
# Check if contour has one partent and one at least on child:
if (h[3] >= 0) and (h[2] >= 0):
# Get the partent from the hierarchy
hp = hier[0][h[3]]
# Check if the parent has a parent:
if hp[3] >= 0:
# Get bounding rectange
x, y, w, h = cv2.boundingRect(c)
# Draw red rectange for testing
cv2.rectangle(img, (x, y), (x w, y h), (0, 0, 255), thickness=1)
# Show result for testing
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
但它選擇影像中的每個輪廓。例如,如果這是原始影像:

那么這就是我運行上面代碼時得到的結果:

我如何,首先,僅檢測此影像中的邊界框,其次,僅突出顯示那些完全 100% 位于另一個邊界框內的邊界框?
uj5u.com熱心網友回復:
步驟 1. 使用 以面積遞增的順序對邊界框進行排序cv2.contourArea。看到這個問題。
第 2 步 - For 回圈 - 從最小的邊界框開始 - 檢查給定框與較大框的交叉區域是否=給定框的面積。如果是,那么它是 100% 在其他更大的盒子里。
例如,我們可以像這樣將邊界框轉換為掩碼:
mask = np.zeros(img.shape[:2], dtype=np.float32)
(x, y, w, h) = [int(v) for v in bounding_box]
mask[y:y h, x:x w] = 1.
然后得到兩個面具的交集面積:
mask1_f = mask1.flatten()
mask2_f = mask2.flatten()
intersection = np.sum(mask1_f * mask2_f)
uj5u.com熱心網友回復:
為了讓一個盒子完全在另一個盒子里面,盒子的每個頂點都應該在更大的盒子里面。您可以使用嵌套的 for 回圈來過濾框以檢查 box2 的所有坐標是否在 box1 的范圍內。
collided_boxes = []
for box1 in boxes:
for box2 in boxes:
if box1 != box2:
if (box1[0] < box2[0] < box1[2] and box1[1] < box2[1] < box1[3]) and (box1[0] < box2[2] < box1[2] and box1[1] < box2[1] < box1[3]) and (box1[0] < box2[2] < box1[2] and box1[1] < box2[3] < box1[3]) and (box1[0] < box2[0] < box1[2] and box1[1] < box2[3] < box1[3]):
if box2 not in collided_boxes:
collided_boxes.append(box2)
在上面,我給出了框的兩個極端角的坐標值,即 [(min x value, min y value) and (max x value, max y value)] 為: box[0] = min x value , box[1] = 最小 y 值,box[2] = 最大 x 值,box[3] = 最大 y 值
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/393763.html
標籤:Python opencv 计算机视觉 边界框 opencv-contour
