pytesser是OCR开源项目的一个模块,在Python中导入这个模块即可将图片中的文字转换成文本。pytesser调用了tesseract。当在Python中调用pytesser模块时,pytesser又用tesseract识别图片中的文字。pytesser的使用步骤如下:
首先,安装Python2.7版本,这个版本比较稳定,建议使用这个版本。
其次,安装pythoncv。
然后,安装PIL工具,pytesser的使用需要PIL库的支持。
接着下载pytesser
最后,将pytesser解压,这个是免安装的,可以将解压后的文件cut到Python安装目录的Lib\site-packages下直接使用,比如我的安装目录是:C:\Python27\Lib\site-packages,同时把这个目录添加到环境变量之中。
完成以上步骤之后,就可以编写图片文本识别的Python脚本了。参考脚本如下:
from pytesser import *
import ImageEnhance
image = Image.open('D:\\workspace\\python\\5.png')
#使用ImageEnhance可以增强图片的识别率
enhancer = ImageEnhance.Contrast(image)
image_enhancer = enhancer.enhance(4)
print image_to_string(image_enhancer)
tesseract是谷歌的一个对图片进行识别的开源框架,免费使用,现在已经支持中文,而且识别率非常高,这里简要来个helloworld级别的认识
下载之后进行安装,不再演示。
在tesseract目录下,有个tesseract.exe文件,主要调用这个执行文件,用cmd运行到这个目录下,在这个目录下同时放置一张需要识别的图片,这里是123.jpg
然后运行:tesseract 123.jpg result
会把123.jpg自动识别并转换为txt文件到result.txt
但是此时中文识别不好
然后找到tessdata目录,把eng.traineddata替换为chi_sim.traineddata,并且把chi_sim.traineddata重命名为eng.traineddata
ok,现在中文识别基本达到90%以上了
# -*- coding: utf-8 -*-import colorsys
def get_dominant_color(image):
#颜色模式转换,以便输出rgb颜色值
image = image.convert('RGBA')
#生成缩略图,减少计算量,减小cpu压力
image.thumbnail((200, 200))
max_score = None
dominant_color = None
for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):
# 跳过纯黑色
if a == 0:
continue
saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
y = (y - 16.0) / (235 - 16)
# 忽略高亮色
if y > 0.9:
continue
# Calculate the score, preferring highly saturated colors.
# Add 0.1 to the saturation so we don't completely ignore grayscale
# colors by multiplying the count by zero, but still give them a low
# weight.
score = (saturation + 0.1) * count
if score > max_score:
max_score = score
dominant_color = (r, g, b)
return dominant_color
if __name__=="__main__":
from PIL import Image
import os
path = r'.\\pics\\'
fp = open('file_color.txt','w')
for filename in os.listdir(path):
print path+filename
try:
color = get_dominant_color(Image.open(path+filename))
fp.write('The color of '+filename+' is '+str(color)+'\n')
except:
print "This file format is not support"
fp.close()
pics文件夹和python程序在一个目录下,产生的文件名file_color.txt也在这个目录下。
看看能否帮到你