After the code acquisition process verification python noise reduction, gradation, save

def convert_image(self):
        = Image.open image_obj ( self.captcha_path ) Get codes #
        img = image_obj.convert ( "L") # turn gray
        pixdata = img.load()
        w, h = img.size
        threshold = 160
        # Traversing all the pixels, is greater than a threshold black
        for y in range(h):
            for x in range(w):
                if pixdata[x, y] < threshold:
                    pixdata [x, y] = 0
                else:
                    pixdata [x, y] = 255
        return img

    def process_image(self):
        images = self.convert_image()
        data = images.getdata()
        w, h = images.size
        black_point = 0
        for x in range(1, w - 1):
            for y in range(1, h - 1):
                mid_pixel = data [w * y + x] # pixel value of the central pixel points
                if mid_pixel <50: # pixel values ​​of the pixels identify the four directions
                    top_pixel = data[w * (y - 1) + x]
                    left_pixel = data[w * y + (x - 1)]
                    down_pixel = data[w * (y + 1) + x]
                    right_pixel = data[w * y + (x + 1)]
                    Analyzing Total # of black pixel number of the vertical and horizontal
                    if top_pixel < 10:
                        black_point += 1
                    if left_pixel < 10:
                        black_point += 1
                    if down_pixel < 10:
                        black_point += 1
                    if right_pixel < 10:
                        black_point += 1
                    if black_point < 1:
                        images.putpixel((x, y), 255)
                    black_point = 0

            images.save(self.process_captcha_path)
        #return images

  

Guess you like

Origin www.cnblogs.com/winstonsias/p/12106671.html