How to create rotated bounding box to an polygon shape

Viewed 163

I tried to create a bounding box for the yellow rectangle in the following picture:original

I already got a code from some tutorials: Code Tutorial

image = cv2.imread('Mask.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
plt.imshow(fixColor(blurred))


canny = cv2.Canny(blurred, 30, 600)
plt.imshow(fixColor(canny))



(cnts, _) = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
coins = image.copy()
cv2.drawContours(coins, cnts, -1, (255, 0, 0), 2)

plt.imshow(fixColor(coins))


for cnt in cnts:
     x,y,w,h = cv2.boundingRect(cnt)
     cv2.rectangle(coins,(x,y),(x+w,y+h),(0,255,0),2)

In the following picture you can see the output of my code:Output bounding box

It creates more than one bounding box, one for the whole picture and some random other ones and I am not sure why. I am thinking about if it is a probleme that it rectangle is not complete in the picture?

Maybe someone have an idea how I can fix it to create only one B-Box for the yellow rectangle.

1 Answers

If you look at your Canny image, you can see the edge of the yellow shape blends with the border of the image, so you will struggle to use an edge detection method such as canny to find your shape when it's not fully contained in the image. Canny image

If you are not restricted to use Canny, I would suggest a simple HSV in range threshold, such as follow:

import numpy as np
import cv2 

image = cv2.imread('image.png')
imagehsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

lower_yellow = np.array([20, 100, 100])
upper_yellow = np.array([30, 255, 255])

mask_yellow = cv2.inRange(imagehsv, lower_yellow, upper_yellow)
contours, hierarchy = cv2.findContours(mask_yellow, cv2.RETR_EXTERNAL, 
                                       cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image, contours, -1, (0, 255, 0), 2, cv2.LINE_AA)

cv2.imshow("contours_yellow", image)

Yellow inRange

Related