3

I am using Opencv and python to detect shapes and then crop them. I have succeeded to do that, however now I am trying to take the cropped images and remove their backgrounds.

The image has a circle inside and surrounded by gray color. (It can be gray or can be even more than one color).

Croped Image

How can I remove the colors surrounding the circle border (which is black) - we can convert the gray color to black - as the border color or even remove it at all and make that transparent.

The result image should contain only the circle.

1

1 Answer 1

5

At least in for this image, there is no need to detect the circle use houghCircle). I think threshold it and find the inner contour , then make mask and do bitwise-op is OK!

My steps:

(1) Read and convert to gray

(2) findContours

(3) find contour that smaller, create a mask

(4) do bitwise_and to crop


Here is my result:

enter image description here


#!/usr/bin/python3
# 2018.01.20 20:58:12 CST
# 2018.01.20 21:24:29 CST
import cv2
import numpy as np

## (1) Read
img = cv2.imread("img04.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

## (2) Threshold
th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

## (3) Find the min-area contour
_cnts = cv2.findContours(threshed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
cnts = sorted(cnts, key=cv2.contourArea)
for cnt in cnts:
    if cv2.contourArea(cnt) > 100:
        break

## (4) Create mask and do bitwise-op
mask = np.zeros(img.shape[:2],np.uint8)
cv2.drawContours(mask, [cnt],-1, 255, -1)
dst = cv2.bitwise_and(img, img, mask=mask)

## Save it
cv2.imwrite("dst.png", dst)
Sign up to request clarification or add additional context in comments.

7 Comments

I am trying since 2 days. Did not succeed. Need help :-( A code can help so I can follow and learn from
Thank you. Unfortunately, this works only if the background is gray. I have tested it with gray background and it works fine, however if the background has more colorful objects so this does not work.- See images attached links. I am new to all of this image processing and openCV .. So be patient with me please :-) In my questions i wrote: "The image has a circle inside and surrounded by gray color. (It can be gray or can be even more than one color)." See the images please here: imgur.com/lQ0XQ8L imgur.com/UaYcH8f
Read the first line of my answer: At least for this image ...
You are right. So if I use the houghCircle which we used for cropping the latest circle image (an image contains the main circle and some more colors on the gray background outside of the circle area) and then mask it will help? Can you give hints and tips here?
To be honest, I will not provide any advice any more, unless your question is clear enough, with all the explicit examples.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.