获取矩形遮罩的真实边界框

2024-04-23 23:50:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二值图像(numpy数组),它表示一个矩形的近似值:

Mask

我试图提取矩形的真实形状,但似乎找不到方法。 预期结果如下:

Exected

我正在使用这个代码

contours,_ = cv2.findContours(numpymask.copy(), 1, 1) # not copying here will throw an error
rect = cv2.minAreaRect(contours[0]) # basically you can feed this rect into your classifier
(x,y),(w,h), a = rect # a - angle

box = cv2.boxPoints(rect)
box = np.int0(box) #turn into ints
rect2 = cv2.drawContours(img.copy(),[box],0,(0,0,255),10)

plt.imshow(rect2)
plt.show()

但我得到的结果如下,我并不需要这些:

enter image description here

为此,我将Python与opencv结合使用


Tags: 方法rect图像numpyboxplt数组cv2
1条回答
网友
1楼 · 发布于 2024-04-23 23:50:00

这是我以前玩过的东西。它应该适合你的形象

import imutils
import cv2
# load the image, convert it to grayscale, and blur it slightly
image = cv2.imread("test.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
# threshold the image,
thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)[1]
# find contours in thresholded image, then grab the largest
# one
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c = max(cnts, key=cv2.contourArea)
# draw the contours of c
cv2.drawContours(image, [c], -1, (0, 0, 255), 2)

# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)

output

相关问题 更多 >