Home > OS >  How to remove bell curved shape from image using opencv
How to remove bell curved shape from image using opencv

Time:02-11

I hope you are doing well. I want to remove the bell-curved shape in the image. I have used OpenCV. I have implemented the following code which detects the curve shape, Now How can remove that curve shape and save the new image in the folder.

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread('the_image.jpg')
ht, wd = img.shape[:2]

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)[1]

# get external contours
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]

max_aspect=0
for cntr in contours:
    x,y,w,h = cv2.boundingRect(cntr)
    aspect = w/h
    if aspect > max_aspect:
        max_aspect = aspect
        max_contour = cntr

# create mask from max_contour
mask = np.zeros((ht,wd), dtype=np.uint8)
mask = cv2.drawContours(mask, [max_contour], 0, (255), -1)

# dilate mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
mask = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)

# invert mask
mask = 255 - mask

# mask out region in input
result = img.copy()
result = cv2.bitwise_and(result, result, mask=mask)

# save resulting image
cv2.imwrite('the_image_masked.png',result)

# show thresh and result    
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

enter image description here

  • Related