Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4446906
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Python/Ruby

2014-08-04 23:15:52

文章来源:http://blog.csdn.net/nwpulei/article/details/8457738

闲话休提,直接开始。

原始图像   



Step 1 打开图像吧。


[python] view plaincopy
  1. im = Image.open('temp1.jpg')  

Step 2 把彩色图像转化为灰度图像。彩色图像转化为灰度图像的方法很多,这里采用RBG转化到HSI彩色空间,采用I分量。


[python] view plaincopy
  1. imgry = im.convert('L')  

灰度看起来是这样的

    

Step 3 需要把图像中的噪声去除掉。这里的图像比较简单,直接阈值化就行了。我们把大于阈值threshold的像素置为1,其他的置为0。对此,先生成一张查找表,映射过程让库函数帮我们做。



[python] view plaincopy
  1. threshold = 140  
  2. table = []  
  3. for i in range(256):  
  4.     if i < threshold:  
  5.         table.append(0)  
  6.     else:  
  7.         table.append(1)  

阈值为什么是140呢?试出来的,或者参考直方图。


映射过程为


[python] view plaincopy
  1. out = imgry.point(table,'1')  


此时图像看起来是这样的

   


Step 4 把图片中的字符转化为文本。采用pytesser 中的image_to_string函数


[python] view plaincopy
  1. text = image_to_string(out)  

Step 5 优化。根据观察,验证码中只有数字,并且上面的文字识别程序经常把8识别为S。因此,对于识别结果,在进行一些替换操作。
[python] view plaincopy
  1. #由于都是数字  
  2. #对于识别成字母的 采用该表进行修正  
  3. rep={'O':'0',  
  4.     'I':'1','L':'1',  
  5.     'Z':'2',  
  6.     'S':'8'  
  7.     };  
[python] view plaincopy
  1. for r in rep:  
  2.     text = text.replace(r,rep[r])  

好了,text中为最终结果。
7025
0195
7039
6716

程序需要和支持。
 
最后,整个程序看起来是这样的
[python] view plaincopy
  1. import Image  
  2. import ImageEnhance  
  3. import ImageFilter  
  4. import sys  
  5. from pytesser import *  
  6.   
  7. # 二值化  
  8. threshold = 140  
  9. table = []  
  10. for i in range(256):  
  11.     if i < threshold:  
  12.         table.append(0)  
  13.     else:  
  14.         table.append(1)  
  15.   
  16. #由于都是数字  
  17. #对于识别成字母的 采用该表进行修正  
  18. rep={'O':'0',  
  19.     'I':'1','L':'1',  
  20.     'Z':'2',  
  21.     'S':'8'  
  22.     };  
  23.   
  24. def  getverify1(name):  
  25.       
  26.     #打开图片  
  27.     im = Image.open(name)  
  28.     #转化到亮度  
  29.     imgry = im.convert('L')  
  30.     imgry.save('g'+name)  
  31.     #二值化  
  32.     out = imgry.point(table,'1')  
  33.     out.save('b'+name)  
  34.     #识别  
  35.     text = image_to_string(out)  
  36.     #识别对吗  
  37.     text = text.strip()  
  38.     text = text.upper();  
  39.   
  40.     for r in rep:  
  41.         text = text.replace(r,rep[r])  
  42.   
  43.     #out.save(text+'.jpg')  
  44.     print text  
  45.     return text  
  46. getverify1('v1.jpg')  
  47. getverify1('v2.jpg')  
  48. getverify1('v3.jpg')  
  49. getverify1('v4.jpg')  
阅读(1011) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~