Gaurav
Gaurav

Reputation: 26

Get the count of rectangles in an image

I have an image like the one below, and I want to determine the number of rectangles in the image. I do know how to do this if they were filled.

contours = cv2.findContours(image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if imutils.is_cv2() else contours[1]
print len(contours)

But this does not work if the rectangle is empty.

I also do not know how to fill the rectangles in the image. I know how to fill the contours if they are drawn using OpenCV, but I do not know how to fill empty rectangles already present in the image.

image with three rectangles

Upvotes: 0

Views: 4061

Answers (2)

lqu
lqu

Reputation: 656

Filled or not should not make a difference if you find the outer contours (RETR_EXTERNAL). Following code will give you number 3. enter image description here

canvas = np.zeros(img.shape, np.uint8)
img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(img2gray,128,255,cv2.THRESH_BINARY_INV)
im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

print(len(contours))

for cont in contours:
    cv2.drawContours(canvas, cont, -1, (0, 255, 0), 3)

cv2.imshow('contours',canvas)
cv2.waitKey(30000)
cv2.destroyAllWindows()

Notice if you use RETR_TREE as the 2nd parameter in findContours(), you get all 6 contours, including the inner ones. enter image description here

Obviously, this assumes that the image only contains rectangles and it doesn't distinguish different shapes.

Upvotes: 1

Shawn Mathew
Shawn Mathew

Reputation: 2337

Assuming you have tried shape detectors, line detections, etc and not succeeded here is another way of solving this problem.

If this is a grayscale PNG image, you can use segmentation by color to achieve this. I would approach it like so:

count = 0
For each pixel in the image:
    if color(pixel) == white /*255*/
        count++
        floodfill using this pixel as a seed pixel and target color as count

no_of_rectangles = count - 1 /* subtract 1 since the background will be colored too*/

This assumes the rectangles have continuous lines, else the floodfill will leak into other rectangles.

Upvotes: 2

Related Questions