Получите настоящий ограничивающий прямоугольник в форме маски - PullRequest
0 голосов
/ 24 апреля 2020

У меня есть это двоичное изображение (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.

1 Ответ

1 голос
/ 24 апреля 2020

Это то, с чем я играл раньше. Он должен работать с вашим изображением.

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

...