J.Doe
J.Doe

Reputation: 85

Removing contours from an image

I have contours which i want to delete from the image, What is the best way to do it ?

image = cv2.imread(path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
retr , thresh = cv2.threshold(gray_image, 190, 255, cv2.THRESH_BINARY_INV)
contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    if cv2.contourArea(c) > 20:
        x, y, w, h = cv2.boundingRect(c)
         ##### how to continue from here  ? 

Upvotes: 1

Views: 8272

Answers (1)

J.D.
J.D.

Reputation: 4561

Create an empty mask in the size of the image:
mask = np.zeros(image.shape[:2], dtype=image.dtype)

Next draw all the contours / boundingrect you want to keep on this mask:
cv2.drawContours(mask, [cnt], 0, (255), -1)
Alternatively you can instead draw the contours you don't want and inverse the mask (this may be more suitable in some situations):
mask= cv2.bitwise_not(mask)

Use the mask on the main image: result = cv2.bitwise_and(image,image, mask= mask)

Edit: added code after comment.

I assumed this is about the image in your other question, so I applied the code to that image.

Result:

enter image description here

Code:

import numpy as np 
import cv2
# load image
image = cv2.imread('image.png')
# create grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# perform threshold
retr , thresh = cv2.threshold(gray_image, 190, 255, cv2.THRESH_BINARY_INV)
# find contours
ret, contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# create emtpy mask
mask = np.zeros(image.shape[:2], dtype=image.dtype)

# draw all contours larger than 20 on the mask
for c in contours:
    if cv2.contourArea(c) > 20:
        x, y, w, h = cv2.boundingRect(c)
        cv2.drawContours(mask, [c], 0, (255), -1)

# apply the mask to the original image
result = cv2.bitwise_and(image,image, mask= mask)

#show image
cv2.imshow("Result", result)
cv2.imshow("Image", image)

cv2.waitKey(0)
cv2.destroyAllWindows() 

Upvotes: 1

Related Questions