python - opencv morphologyEx remove specific color

前端 未结 2 1816
梦毁少年i
梦毁少年i 2021-01-03 03:55

After remove captcha\'s background.
The image remain digits and noise.
Noise line is all in one color : RGB(127,127,127)
And then using morphology method.

2条回答
  •  爱一瞬间的悲伤
    2021-01-03 03:58

    Here is my solution.
    Your answer is obvious better than my.

     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)
    

    final result:

提交回复
热议问题