I have a problem about how to find the biggest rectangle among these small rectangles in contours opencv please help me
Here is the small rectangles from cv2.findContours() I got a list of contours. I plot it and I got this
I want the yellow rectangle box
This is the codes
img_grey = cv2.cvtColor(bg_img,cv2.COLOR_BGR2GRAY)
ret,thresh_img = cv2.threshold(img_grey, 100, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
Does it have a way to find the big rectangle(yellow) Thank you
CodePudding user response:
You need to proceed from where you left after finding contours.
Approach:
- Initialize an array
- Iterate through each contour and store its points in the array
- Find the maximum and minimum values in both axis (
numpy
is your friend!) - Draw a rectangle using them.
Code:
# create copy of original color image
img2 = bg_img.copy()
# Initialize array with value (0,0)
cc = np.array([[0, 0]], dtype=int)
# Iterate through each contour
for i, c in enumerate(contours):
# reshape from (L, 1, 2) to (L, 2), where L is a tuple of (x, y)
c_modified = c.reshape(len(contours[i]), 2)
# concatenate to initial array
cc = np.concatenate((cc, c_modified), axis = 0)
# remove the first element of initialized array
new_cc = cc[1:]
# obtain max and min value along Y-axis
y2 = np.max(new_cc[:,1])
y1 = np.min(new_cc[:,1])
# obtain max and min value along X-axis
x2 = np.max(new_cc[:,0])
x1 = np.min(new_cc[:,0])
# Draw rectangle using those points on copy of the image
img2 = cv2.rectangle(img2, (x1, y1), (x2, y2), (255,255, 0, 3)
Result: