如何使用opencv从图像中去除钟形曲线

How to remove bell curved shape from image using opencv

希望你一切顺利。我想删除图像中的钟形曲线。我用过 OpenCV。我已经实现了以下检测曲线形状的代码,现在如何删除该曲线形状并将新图像保存在文件夹中。

Input Image 1

我要删除下图中显示的区域

Area i want to remove

import cv2 
import numpy as np
    # load image as grayscale
cell1 = cv2.imread("/content/savedImage.jpg",0)
    # threshold image
ret,thresh_binary = cv2.threshold(cell1,107,255,cv2.THRESH_BINARY)
    # findcontours
contours, hierarchy = cv2.findContours(image =thresh_binary , mode = cv2.RETR_TREE,method = cv2.CHAIN_APPROX_SIMPLE)

    # create an empty mask
mask = np.zeros(cell1.shape[:2],dtype=np.uint8)

    # loop through the contours
for i,cnt in enumerate(contours):
            # if the contour has no other contours inside of it
    if hierarchy[0][i][2] == -1 :
                    # if the size of the contour is greater than a threshold
       if  cv2.contourArea(cnt) > 10000:
             cv2.drawContours(mask,[cnt], 0, (255), -1)   
fig, ax = plt.subplots(1,2)
ax[0].imshow(cell1,'gray');
ax[1].imshow(mask,'gray');

Ouput Image after the above Code

我怎样才能去除那个曲线形状?

这是 Python/OpenCV 中的一种方法。

获取外部轮廓。然后找到具有最大 w/h 纵横比的那个。绘制填充在黑色背景上的轮廓作为蒙版。稍微扩张一下。然后将其反转并用它来涂黑该区域。

输入:

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()

结果: