Reputation: 91
I'm trying to draw the minimum box outline on a simple image.
However, one of the points returned from the boxPoints() function gives me a negative y value. When drawing this contour, this corner is drawn off the image.
I'm not sure why it returns a negative y value. I am using a binary version of the image, so the largest contour should be the outline of the postIt note. One of the other corners is not picked up correctly either. Not too sure how to go about fixing this. See code below:
def contours(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
gray = cv2.dilate(gray, None) # fill some holes
gray = cv2.dilate(gray, None)
gray = cv2.erode(gray, None) # dilate made our shape larger, revert that
gray = cv2.erode(gray, None)
# first threshold the image to create a binary image of black and white
ret, thresh = cv2.threshold(gray, 127, 255, 0)
# contours output var is a list of each coordinate in the contour
# use CHAIN_APPROX_SIMPLE to pick only necessary contour points rather than all points on the contour
img,cnt,hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# get the min area rect
rect = cv2.minAreaRect(cnt[0])
print(rect)
box = cv2.boxPoints(rect)
print(box)
# convert all coordinates floating point values to int
box = np.int32(box)
cv2.drawContours(image, [box], 0, (0, 0, 255))
cv2.imshow('Corners1', image)
cv2.waitKey(0)
The printed minAreaRect and boxPoints are the following:
((182.83834838867188, 139.0049591064453), (208.65762329101562, 247.1478271484375), -31.165145874023438)
[[ 157.5166626 298.73544312]
[ 29.61603546 87.25617981]
[ 208.16003418 -20.7255249 ]
[ 336.06066895 190.7537384 ]]
Upvotes: 1
Views: 1615
Reputation: 188
It looks like you are using a box function in this library. You can see, on the resulting image, all the angles are 90 degrees, so what you need to do is make a polygon not a rectangle. The negative y-value is a result of this right-angled box.
Upvotes: 2