[关闭]
@Dukebf 2017-07-11T16:14:15.000000Z 字数 1555 阅读 1582

python之Pillow使用

python


前人轮子
Pillow 官网

Pillow 是知名的Python图像处理库(Python Image Library,PIL) 的分支版本。
不过 PIL 从2009年开始就再没更新过。

安装

  1. python -m pip install Pillow

使用

Pillow 中有许多处理图片的模块,具体可以查看官网的使用

下面就常用的,用图片demo.jpg举例子,。
demo.jpg

获取 Image 对象,方便对图片处理
比如旋转图片,并将其打开展示

  1. from PIL import Image
  2. im = Image.open("demo.jpg")
  3. im.rotate(45).show()

比如创建缩略图

  1. from PIL import Image
  2. import glob,os
  3. size = 128,128
  4. for infile in glob.glob("*.jpg"):
  5. file,ext = os.path.splitext(infile)
  6. im = Image.open(infile)
  7. im.thumbnail(size)
  8. im.save(file+".thumbnail","JPEG")

获取灰度图像,并将图像中黑色的文本抽离出来,即阈值化,可以用来提取简单的验证码。

  1. from PIL import Image
  2. im = Image.open("demo.jpg")
  3. gray = im.convert('L')
  4. gray.save('demo_gray.jpg')
  5. # 阈值化
  6. bw = gray.point(lambda x: 0 if x < 1 else 255,'1')
  7. bw.save('demo_thresholded.png')

提取验证码

pytesseract 是python中一个开源光学字符识别(OCR)引擎,可以用于从图像中抽取文本。
pytesseract 官网

  1. python -m pip install pytesseract

可以试着提取上面阈值化后的图片

  1. from PIL import Image
  2. import pytesseract
  3. im = Image.open('demo_thresholded.png')
  4. pytesseract.image_to_string(im)

注意:
它可能会返回空字符串,这表明抽取图像的字符串失败了,100张简单验证码中,它的成功率有85%左右。
也可能会因为系统中缺少tesseract-ocr 而报错:

  1. Traceback (most recent call last):
  2. File "<stdin>", line 1, in <module>
  3. File "/usr/local/lib/python2.7/dist-packages/pytesseract/pytesseract.py", line 161, in image_to_string
  4. config=config)
  5. File "/usr/local/lib/python2.7/dist-packages/pytesseract/pytesseract.py", line 94, in run_tesseract
  6. stderr=subprocess.PIPE)
  7. File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
  8. errread, errwrite)
  9. File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
  10. raise child_exception
  11. OSError: [Errno 2] No such file or directory

这时就需要安装tesseract-ocr,安装方法参考来自这里

apt-get install tesseract-ocr

提取成功的例子
demothreshold.png

  1. >>> pytesseract.image_to_string(img)
  2. 'strange'
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注