python - opencv morphologyEx remove specific color

前端 未结 2 1803
梦毁少年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:

    0 讨论(0)
  • 2021-01-03 04:19

    In order to eliminate color within a particular range you have to use cv2.inRange() function.

    Here is the code:

    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)
    

    This is what I got for the two images you have:

    Image 1:

    Image 2:

    You carry on from here.

    0 讨论(0)
提交回复
热议问题