Python - OpenCV形态学操作移除指定

2024-05-15 23:32:44 发布

您现在位置:Python中文网/ 问答频道 /正文

删除验证码背景后。
图像保留数字和噪声。
噪声线全部为一种颜色:RGB(127127127)
然后用形态学的方法。

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
    self.im = cv2.morphologyEx(self.im, cv2.MORPH_CLOSE, kernel)

数字的某些部分将被删除。
如何使用morphologyEx()在RGB(127127127)中仅删除颜色?

enter image description hereenter image description here


Tags: 方法图像self颜色数字rgbcv2噪声
2条回答

这是我的解决方案。
你的回答显然比我的好。

 def mop_close(self):
    def morphological(operator=min):
        height, width, _ = self.im.shape
        # create empty image
        out_im = np.zeros((height,width,3), np.uint8)
        out_im.fill(255) # fill with white
        for y in range(height):
            for x in range(width):
                try:
                    if self.im[y,x][0] ==127 and self.im[y,x][1] ==127 and self.im[y,x][2] ==127:
                        nlst = neighbours(self.im, y, x)

                        out_im[y, x] = operator(nlst,key = lambda x:np.mean(x))
                    else:
                        out_im[y,x] = self.im[y,x]
                except Exception as e:
                    print(e)
        return out_im

    def neighbours(pix,y, x):
        nlst = []
        # search pixels around im[y,x] add them to nlst
        for yy in range(y-1,y+1):
            for xx in range(x-1,x+1):
                try:
                    nlst.append(pix[yy, xx])
                except:
                    pass
        return np.array(nlst)

    def erosion(im):
        return morphological(min)

    def dilation(im):
        return morphological(max)

    self.im = dilation(self.im)
    self.im = erosion(self.im)

最终结果: enter image description hereenter image description here

为了消除特定范围内的颜色,必须使用cv2.inRange()函数。

代码如下:

lower = np.array([126,126,126])  #-- Lower range --
upper = np.array([127,127,127])  #-- Upper range --
mask = cv2.inRange(img, lower, upper)
res = cv2.bitwise_and(img, img, mask= mask)  #-- Contains pixels having the gray color--
cv2.imshow('Result',res)

这是我从你的两张照片中得到的:

图1:

enter image description here

图2:

enter image description here

你从这里继续。

相关问题 更多 >