Ask Your Question
0

How to find contours of white object having little bit of black object?

asked 2019-02-16 12:57:35 -0500

bumzo gravatar image

updated 2019-02-16 20:51:21 -0500

I have white background with a black filled rectangle in the center. I need to have contours of white regions. cv2.findContours gives one full contour of the whole image. How to use this cv2.findContours function?

import numpy as np

import cv2

white_img = np.ones((190, 640, 3), np.uint8) * 255

(rows, cols, channels) = white_img.shape

gray = cv2.cvtColor(white_img, cv2.COLOR_BGR2GRAY)

cv2.rectangle(gray, (320, 100), (380, 190), (0, 0, 0), cv2.FILLED)

contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

print(len(contours))

for c in contours:

    x, y, w, h = cv2.boundingRect(c)

    cv2.rectangle(white_img, (x, y), (x + w, y + h), (0, 0, 255), 3)

cv2.imshow('white_img', white_img)

cv2.waitKey(0)

Input Image

image description

Output should be like this

image description

Other input could be like

image description

Its output should be

image description

edit retag flag offensive close merge delete

Comments

1

For each column, check height of black section. If height changes, then start a new box. Or something close to that.

sjhalayka gravatar imagesjhalayka ( 2019-02-16 14:33:48 -0500 )edit

it is not necessary that the black object is a rectangle only. It could be of any shape.

bumzo gravatar imagebumzo ( 2019-02-16 20:41:46 -0500 )edit

1 answer

Sort by ยป oldest newest most voted
0

answered 2019-02-16 18:30:27 -0500

import numpy as np

import cv2

white_img = np.ones((190, 640, 3), np.uint8) * 255

(rows, cols, channels) = white_img.shape

gray = cv2.cvtColor(white_img, cv2.COLOR_BGR2GRAY)

cv2.rectangle(gray, (320, 100), (380, 190), (0, 0, 0), cv2.FILLED)
edges = cv2.Canny(gray,100,200)
cv2.imshow('gray', edges)
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

print(len(contours))

for c in contours:

    x, y, w, h = cv2.boundingRect(c)

    cv2.rectangle(white_img, (x, y), (x + w, y + h), (0, 0, 255), -1)
    cv2.rectangle(white_img, (0, 0), (x, y + h), (0, 255, 0), -1)
    cv2.rectangle(white_img, (x, 0), ( x+ w, y), (255, 0, 0), -1)
    cv2.rectangle(white_img, (white_img.shape[1] - x + w, 0), (white_img.shape[1], white_img.shape[0]), (255, 255, 0), -1)
cv2.imshow('white_img', white_img)

cv2.waitKey(0)
edit flag offensive delete link more

Comments

I am looking for a general solution. what if there is more than a black rectangle or what if the black object is triangle?

bumzo gravatar imagebumzo ( 2019-02-16 20:48:02 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2019-02-16 12:57:35 -0500

Seen: 42 times

Last updated: Feb 16