Python3实现的简单验证码识别功能示例

日期: 2019-12-06 15:14 浏览次数 :

正文实例汇报了Python3得以达成的简便验证码识别效用。分享给咱们供我们参谋,具体如下:

正文实例呈报了Python2.7+pytesser完毕不难验证码的识别方法。分享给大家供大家参照他事他说加以考察,具体如下:

Python3实现的简单验证码识别功能示例。正文实例陈诉了Python完成PS滤镜的团团转模糊效能。分享给大家供大家参谋,具体如下:

此次的急需是机关登入某部门网址, 其验证码很具特点, 很适合做验证码识别入门demo, 先贴首要代码, 此中图片比较使用了编写制定距离算法, 脚本使用了pillow库

首先,安装Python2.7版本

此间用 Python 完毕 PS 滤镜中的旋转模糊,具体的算法原理和效用可以参照附录相关介绍。Python代码如下:

from PIL import Image
import requests
import re
splitter = re.compile(r'd{30}') # 分割二值化后的图片
# distance('11110000', '00000000')
# 比较两个字符串有多少位不同, 返回不同的位数
def distance(string1, string2):
  d_str1 = len(string1)
  d_str2 = len(string2)
  d_arr = [[0] * d_str2 for i in range(d_str1)]
  for i in range(d_str1):
    for j in range(d_str2):
      if string1[i] == string2[j]:
        if i == 0 and j == 0:
          d_arr[i][j] = 0
        elif i != 0 and j == 0:
          d_arr[i][j] = d_arr[i - 1][j]
        elif i == 0 and j != 0:
          d_arr[i][j] = d_arr[i][j - 1]
        else:
          d_arr[i][j] = d_arr[i - 1][j - 1]
      else:
        if i == 0 and j == 0:
          d_arr[i][j] = 1
        elif i != 0 and j == 0:
          d_arr[i][j] = d_arr[i - 1][j] + 1
        elif i == 0 and j != 0:
          d_arr[i][j] = d_arr[i][j - 1] + 1
        else:
          d_arr[i][j] = min(d_arr[i][j - 1], d_arr[i - 1][j], d_arr[i - 1][j - 1]) + 1
  current = max(d_arr[d_str1 - 1][d_str2 - 1], abs(d_str2 - d_str1))
  # print("Levenshtein Distance is",current)
  # print(current)
  return current
# 去除字符串里面连续的1
def no_one(string):
  n_arr = splitter.findall(string)
  n_arr = filter(lambda each_str: each_str != '111111111111111111111111111111', n_arr)
  n_result = ''
  for n_each in n_arr:
    n_result += str(n_each)
  return n_result
opener = requests.session()
res = opener.get('http://60.211.254.236:8402/Ajax/ValidCodeImg.ashx').content
with open('verify.gif', 'wb') as v:
  v.write(res)
img = Image.open('verify.gif')
img = img.convert('L')
size = img.size
# img = img.point(table, '1')
img_arr = img.load()
# for x in range(size[0]):
#   for y in range(size[1]):
#     if img_arr[x, y] > 210:
#       img_arr[x, y] = 1
#     else:
#       img_arr[x, y] = 0
# img.save('after.gif')
inc = 0
str1 = ''
str2 = ''
str3 = ''
cur_str = ''
for x in range(size[0]):
  for y in range(size[1]):
    if img_arr[x, y] > 210:
      cur_str += '1'
    else:
      cur_str += '0'
    # print(img_arr[i, j], end='')
    # cur_str += str(img_arr[x, y])
  inc += 1
  # if inc % 18 == 0:
  #   print('n----')
  # else:
  #   print('')
  if inc == 18:
    str1 = cur_str
    cur_str = ''
  elif inc == 36:
    str2 = cur_str
    cur_str = ''
  elif inc == 54:
    str3 = cur_str
    cur_str = ''
str1 = str1[:-60]
str2 = str2[:-60]
str3 = str3[:-60]
str1 = no_one(str1)
str2 = no_one(str2)
str3 = no_one(str3)
str1 = str1.strip('1')
str2 = str2.strip('1')
str3 = str3.strip('1')
# print(str1)
# print(str3)
with open('./dict/plus') as plus:
  with open('./dict/minus') as minus:
    p = plus.read()
    m = minus.read()
    is_add = 1 if distance(p, str2) < distance(m, str2) else 0
arr1 = []
arr3 = []
for each in range(1, 10):
  with open('./dict/{}'.format(each)) as f:
    ff = f.read()
    arr1.append([each, distance(ff, str1)])
    arr3.append([each, distance(ff, str3)])
arr1 = sorted(arr1, key=lambda item: item[1])
arr3 = sorted(arr3, key=lambda item: item[1])
result = arr1[0][0] + arr3[0][0] if is_add else arr1[0][0] - arr3[0][0]
print(result)
# login_url = 'http://60.211.254.236:8402/Ajax/Login.ashx?Method=G3_Login'
# login_data = {
#   'loginname': usn,
#   'password': pwd,
#   'validcode': result,
#
# }
# opener.get(login_url, login_data)

然后,安装PIL工具,下载的地方是:,pytesser的应用供给PIL库的支撑。

from skimage import img_as_float
import matplotlib.pyplot as plt
from skimage import io
import numpy as np
import numpy.matlib
file_name='D:/Visual Effects/PS Algorithm/4.jpg'
img=io.imread(file_name)
img = img_as_float(img)
img_out = img.copy()
row, col, channel = img.shape
xx = np.arange (col)
yy = np.arange (row)
x_mask = numpy.matlib.repmat (xx, row, 1)
y_mask = numpy.matlib.repmat (yy, col, 1)
y_mask = np.transpose(y_mask)
center_y = (row -1) / 2.0
center_x = (col -1) / 2.0
R = np.sqrt((x_mask - center_x) **2 + (y_mask - center_y) ** 2)
angle = np.arctan2(y_mask - center_y , x_mask - center_x)
Num = 20
arr = ( np.arange(Num) + 1 ) / 100.0
for i in range (row):
  for j in range (col):
    T_angle = angle[i, j] + arr
    new_x = R[i, j] * np.cos(T_angle) + center_x
    new_y = R[i, j] * np.sin(T_angle) + center_y
    int_x = new_x.astype(int)
    int_y = new_y.astype(int)
    int_x[int_x > col-1] = col - 1
    int_x[int_x < 0] = 0
    int_y[int_y < 0] = 0
    int_y[int_y > row -1] = row -1
    img_out[i,j,0] = img[int_y, int_x, 0].sum()/Num
    img_out[i,j,1] = img[int_y, int_x, 1].sum()/Num
    img_out[i,j,2] = img[int_y, int_x, 2].sum()/Num
plt.figure(1)
plt.imshow(img)
plt.axis('off')
plt.figure(2)
plt.imshow(img_out)
plt.axis('off')
plt.show()

字库已经安顿到GitHub地址:

随之下载pytesser,下载的地址是:

附:PS 滤镜——旋转模糊

更多关于Python相关内容感兴趣的读者可查看本站专项论题:《Python图片操作技术总括》、《Python数据布局与算法教程》、《Python Socket编程技艺总括》、《Python函数使用能力计算》、《Python字符串操作手艺汇总》、《Python入门与进级杰出教程》及《Python文件与目录操作工夫汇总》

是因为code.google.com网站十分小概访谈。可点击这里本站下载.rar)。

此处给出灰度图像的歪曲算法,彩图只要分别对多少个通道做模糊就可以。

意在本文所述对大家Python程序设计有所扶持。

最后,安装pytesser :

%% spin blur
% 旋转模糊
clc;
clear all;
close all;
I=imread('4.jpg');
I=double(I);
% % % I_new=I;
% % % for kk=1:3
% % %   I_new(:,:,kk)=Spin_blur_Fun(I(:,:,kk), 30, 30);
% % % end
% % % imshow(I_new/255)
Image=I;
Image=0.2989 * I(:,:,1) + 0.5870 * I(:,:,2) + 0.1140 * I(:,:,3);
[row, col]=size(Image);
Image_new=Image;
Center_X=(col+1)/2;
Center_Y=(row+1)/2;
validPoint=1;
angle=5;
radian=angle*pi/180;
radian2=radian*radian;
Num=30;
Num2=Num*Num;
for i=1:row
  for j=1:col
    validPoint=1;
    x0=j-Center_X;
    y0=Center_Y-i;
    x1=x0;
    y1=y0;
    Sum_Pixel=Image(i,j);
    for k=1:Num
      x0=x1;
      y0=y1;
      %%% 逆时针
      % x1=x0-radian*y0/Num-radian2*x0/Num2;
      % y1=y0+radian*x0/Num-radian2*y0/Num2;
      %%% 顺时针
      x1=x0+radian*y0/Num-radian2*x0/Num2;
      y1=y0-radian*x0/Num-radian2*y0/Num2;
      x=floor(x1+Center_X);
      y=floor(Center_Y-y1);
      if(x>1 && x<col && y>1 && y<row)
        validPoint=validPoint+1;
        Sum_Pixel=Sum_Pixel+Image(y,x);
      end
    end
    Image_new(i,j)=Sum_Pixel/validPoint;
  end
end
 imshow(Image_new/255);