使用pytesseract+tesseract来识别验证码的尝试,识别率是真的低啊。

# -*- coding: utf-8 -*-
from PIL import Image, ImageEnhance
import pytesseract
import pytesser3
import pytesser
import time

class ValidateImageCode():
    def __init__(out):
        pass
    def Image_to_String(out,x,y,width,height):
       # 采用二值法去除背景色
       rangle = (int(x), int(y), int(x + int(width)), int(y + int(height))) #写成我们需要截取的位置坐标
       i=Image.open("D://aa.png")   #打开截图
       frame4=i.crop(rangle)  #使用Image的crop函数,从截图中再次截取我们需要的区域
       frame4.save('D://frame4.png')
       time.sleep(3)
       img = Image.open('D://frame4.png')
       #imgry = img.convert("L")
       imgry = img.convert("RGB")
       WHITE = (255, 255, 255)
       BLACK = (0, 0, 0)
       width, height = imgry.size
       threshold = 140            #决定出图质量的阈值,只要这个值才最优化
       for i in range(0, width):
           for j in range(0, height):
               p = imgry.getpixel((i, j))  # 抽取坐标(i,j)出像素点的RGB颜色值
               r, g, b = p
               if r > threshold or g > threshold or b > threshold:
                   imgry.putpixel((i, j), WHITE)#设置坐标(i,j)处像素点的RGB颜色值为(255.255.255)
               else:
                   imgry.putpixel((i, j), BLACK)
       imgry.save('D:\\imgry.png')
       out = Image.open('D:\\imgry.png')
       sharpness = ImageEnhance.Contrast(out)  # 对比度增强
       sharp_img = sharpness.enhance(2.0)
       sharp_img.save('D:\\out.png')
       out = Image.open('D:\\out.png')
       # 采用中值滤波法去除椒盐噪点
       window=1
       if window == 1:    #十字型滑动窗口
           window_x = [1, 0, 0, -1, 0]
           window_y = [0, 1, 0, 0, -1]
       elif window == 2:   #矩形滑动窗口
           window_x = [-1, 0, 1, -1, 0, 1, 1, -1, 0]
           window_y = [-1, -1, -1, 1, 1, 1, 0, 0, 0]
       width, height = out.size
       for i in range(width):
           for j in range(height):
               box = []
               for k in range(len(window_x)):
                   d_x = i + window_x[k]
                   d_y = j + window_y[k]
                   try:
                       d_point = out.getpixel((d_x, d_y))
                       if d_point == BLACK:
                           box.append(1)
                       else:
                           box.append(0)
                   except IndexError:
                       out.putpixel((i, j), WHITE)
                       continue
               box.sort()
               if len(box) == len(window_x):
                   mid = box[int(len(box) / 2)]
                   if mid == 1:
                       out.putpixel((i, j), BLACK)
                   else:
                       out.putpixel((i, j), WHITE)

       #out.show()
       out.save('D:\\outfinal.png')
       aa = pytesseract.image_to_string(out)
       aa = aa.strip()
       aa = aa.replace(" ","")
       aa = aa[:4]
       print (u"识别的验证码为:")
       return aa
if __name__ == "__main__":
   a = ValidateImageCode().Image_to_String()
   print (a)

你可能感兴趣的:(自动化测试)