@Dukebf
2017-07-11T16:14:15.000000Z
字数 1555
阅读 1879
python
前人轮子
Pillow 官网
Pillow 是知名的Python图像处理库(Python Image Library,PIL) 的分支版本。
不过 PIL 从2009年开始就再没更新过。
python -m pip install Pillow
Pillow 中有许多处理图片的模块,具体可以查看官网的使用。
下面就常用的,用图片demo.jpg举例子,。

获取 Image 对象,方便对图片处理
比如旋转图片,并将其打开展示
from PIL import Imageim = Image.open("demo.jpg")im.rotate(45).show()
比如创建缩略图
from PIL import Imageimport glob,ossize = 128,128for infile in glob.glob("*.jpg"):file,ext = os.path.splitext(infile)im = Image.open(infile)im.thumbnail(size)im.save(file+".thumbnail","JPEG")
获取灰度图像,并将图像中黑色的文本抽离出来,即阈值化,可以用来提取简单的验证码。
from PIL import Imageim = Image.open("demo.jpg")gray = im.convert('L')gray.save('demo_gray.jpg')# 阈值化bw = gray.point(lambda x: 0 if x < 1 else 255,'1')bw.save('demo_thresholded.png')
pytesseract是python中一个开源光学字符识别(OCR)引擎,可以用于从图像中抽取文本。
pytesseract 官网
python -m pip install pytesseract
可以试着提取上面阈值化后的图片
from PIL import Imageimport pytesseractim = Image.open('demo_thresholded.png')pytesseract.image_to_string(im)
注意:
它可能会返回空字符串,这表明抽取图像的字符串失败了,100张简单验证码中,它的成功率有85%左右。
也可能会因为系统中缺少tesseract-ocr 而报错:
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/usr/local/lib/python2.7/dist-packages/pytesseract/pytesseract.py", line 161, in image_to_stringconfig=config)File "/usr/local/lib/python2.7/dist-packages/pytesseract/pytesseract.py", line 94, in run_tesseractstderr=subprocess.PIPE)File "/usr/lib/python2.7/subprocess.py", line 711, in __init__errread, errwrite)File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_childraise child_exceptionOSError: [Errno 2] No such file or directory
这时就需要安装tesseract-ocr,安装方法参考来自这里
apt-get install tesseract-ocr
提取成功的例子

>>> pytesseract.image_to_string(img)'strange'