python 图片验证码去噪 识别

二值化处理(图片默认在C:\Python27\Scripts文件夹下,可根据自己需求更改)

原图:


from PIL import Image  
  
# 二值化处理  
def two_value():    
        # 打开文件夹中的图片  
        image=Image.open('3.jpg')  
        # 灰度图  
        lim=image.convert('L')  
        # 灰度阈值设为165,低于这个值的点全部填白色  
        threshold=165
        table=[]  
          
        for j in range(256):  
            if j

二值化:

对于有干扰线的图片先二值化再进行去干扰线操作

from PIL import Image  
  
# 去除干扰线  
im = Image.open('4.jpg')  
# 图像二值化  
data = im.getdata()  
w,h = im.size  
black_point = 0  
  
for x in range(1,w-1):  
    for y in range(1,h-1):  
        mid_pixel = data[w*y+x] # 中央像素点像素值  
        if mid_pixel <50: # 找出上下左右四个方向像素点像素值  
            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)]  
  
            # 判断上下左右的黑色像素点总个数  
            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:  
                im.putpixel((x,y),255)  
            # print(black_point)  
            black_point = 0  
            
im.save('4.jpg')  

去噪算法(8邻域降噪)

#coding:utf-8  
import sys,os  
from PIL import Image,ImageDraw  
  
#二值判断,如果确认是噪声,用改点的上面一个点的灰度进行替换  
#该函数也可以改成RGB判断的,具体看需求如何  
def getPixel(image,x,y,G,N):  
    L = image.getpixel((x,y))  
    if L > G:  
        L = True  
    else:  
        L = False  
  
    nearDots = 0  
    if L == (image.getpixel((x - 1,y - 1)) > G):  
        nearDots += 1  
    if L == (image.getpixel((x - 1,y)) > G):  
        nearDots += 1  
    if L == (image.getpixel((x - 1,y + 1)) > G):  
        nearDots += 1  
    if L == (image.getpixel((x,y - 1)) > G):  
        nearDots += 1  
    if L == (image.getpixel((x,y + 1)) > G):  
        nearDots += 1  
    if L == (image.getpixel((x + 1,y - 1)) > G):  
        nearDots += 1  
    if L == (image.getpixel((x + 1,y)) > G):  
        nearDots += 1  
    if L == (image.getpixel((x + 1,y + 1)) > G):  
        nearDots += 1  
  
    if nearDots < N:  
        return image.getpixel((x,y-1))  
    else:  
        return None  
  
# 降噪   
# 根据一个点A的RGB值,与周围的8个点的RBG值比较,设定一个值N(0 
对于有干扰线的效果依旧不行,识别正确率较低。

你可能感兴趣的:(python)