Python 操作图片识别,对比,验证码之PIL,pytesseract

By | April 23, 2021

安装python包

pip3 install pillow
pip3 install pytesseract

pytesseract的使用需要安装对应的Tesseract-OCR程序,无论是windows系统还是Lunix系统,都可以到GitHub下载相关版本。
链接:https://github.com/tesseract-ocr/tesseract/
安装完成后,把你安装tesseract的路径添加到你电脑的环境变量path中,
或者修改pytesseract.py文件,指定tesseract.exe安装路径

# CHANGE THIS IF TESSERACT IS NOT IN YOUR PATH, OR IS NAMED DIFFERENTLY
tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'

或者在实际运行中指定路径

pytesseract.pytesseract.tesseract_cmd = 'D:\\Program Files\\Tesseract-OCR\\tesseract.exe'

读取图片里面文字:

from PIL import Image
import pytesseract

img = Image.open('test1.png')
text = pytesseract.image_to_string(img, lang='eng')
print(text)

image_to_string函式有一个关键字引数 lang,默认是英文,可以改变成你想要的语言字串

pytesseract.image_to_string(img, lang='eng',config='--psm 11 -c tessedit_char_whitelist=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')

psm各个数字的含义:

0仅限方向和脚本检测(OSD)。
1使用OSD自动分页。
2自动页面分割,但没有OSD或OCR。
3全自动页面分割,但没有OSD。 (默认)
4假设一列可变大小的文本。
5假设一个垂直对齐文本的统一块。
6假设一个统一的文本块。
7将图像视为单个文本行。
8将图像视为单个单词。
9将图像视为圆形中的单个单词。
10将图像视为单个字符。
11稀疏文字。 找到尽可能多的文本,没有特定的顺序。
12带OSD的稀疏文本。
13原始线。 将图像视为单个文本行

附: 两个图片对比代码,值越接近于1越相近

class CompareImage():
    def calculate(self, image1, image2):
        g = image1.histogram()
        s = image2.histogram()
        assert len(g) == len(s), "error"
        data = []
        for index in range(0, len(g)):
            if g[index] != s[index]:
                data.append(1 - abs(g[index] - s[index]) / max(g[index], s[index]))
            else:
                data.append(1)
        return sum(data) / len(g)

    def split_image(self, image, part_size):
        pw, ph = part_size
        w, h = image.size
        sub_image_list = []
        assert w % pw == h % ph == 0, "error"
        for i in range(0, w, pw):
            for j in range(0, h, ph):
                sub_image = image.crop((i, j, i + pw, j + ph)).copy()
                sub_image_list.append(sub_image)
        return sub_image_list

    def compare_image(self, file_image1, file_image2, size=(256, 256), part_size=(64, 64)):
        '''
        'file_image1'和'file_image2'是传入的文件路径
         可以通过'Image.open(path)'创建'image1' 和 'image2' Image 对象.
         'size' 重新将 image 对象的尺寸进行重置,默认大小为256 * 256 .
         'part_size' 定义了分割图片的大小.默认大小为64*64 .
         返回值是 'image1' 和 'image2'对比后的相似度,相似度越高,图片越接近,达到1.0说明图片完全相同。
        '''

        image1 = Image.open(file_image1)
        image2 = Image.open(file_image2)
        img1 = image1.resize(size).convert("RGB")
        sub_image1 = self.split_image(img1, part_size)
        img2 = image2.resize(size).convert("RGB")
        sub_image2 = self.split_image(img2, part_size)
        sub_data = 0
        for im1, im2 in zip(sub_image1, sub_image2):
            sub_data += self.calculate(im1, im2)
        x = size[0] / part_size[0]
        y = size[1] / part_size[1]
        pre = round((sub_data / (x * y)), 6)
        # print(str(pre * 100) + '%')
        print('Compare the image result is: ' + str(pre))
        return pre
       
        # # compare_image.compare_image("1.jpg", "2.jpg")
        res = compare_image.compare_image('img1.png','img2.png')
        print(res)

Leave a Reply