【收藏】图片转成文字的方法总结,python批量图片转文字信息参考源码

在日常办公或者学习中,往往存在这样一个工作场景,比如,“老王,我这里有一张图片,你把里面的文字信息给我整理出来”,都2021年了,你真的还在手敲图片文字信息么?那么还不赶紧收藏这篇秘籍,这里本渣渣总结了三种方法,教你如何将图片上的文字信息提取出来,图片转成文字信息的方法。

pic_001.png

方法一:QQ/微信聊天工具

对,你没看错,就是QQ聊天工具,新版本的微信也已经支持图片提取文字信息了,同时也支持翻译,相信大部分人应该已经使用过,而且效果也非常出色!

pic_002.png

该方法更适合移动端操作,识别效果也很给力,推荐操作使用!

pic_003.png

方法二:网上在线图文识别工具

直接百度搜索可以找到不少图文识别工具,大部分应该是调用接口封装而成的网页工具,操作相比第一种会繁琐一些,毕竟你需要上传文件,然后再下载文件。

pic_004.png

比如:http://www.pdfdo.com/image-to-txt.aspx

该方法大家可以尝试一下,网上有不少这样的工具,图片识别量小可以免费使用,小心被割韭菜即可,当然识别率并非百分百,不妨参考尝试使用!

方法三:应用Python写图片识别文字工具(骚操作,仅供装比使用)

骚操作来了,我们可以应用python来自己写一个工具脚本,一个图片识别文字工具脚本,可以批量操作,解放双手,当然仅供装比使用,当然本渣渣这么菜,肯定是直接调用接口啦!

方法一:EasyOCR库

Python中有一个不错的OCR库-EasyOCR,在GitHub已有9700star。它可以在python中调用,用来识别图像中的文字,并输出为文本。

https://github.com/JaidedAI/EasyOCR

pic_007.png

EasyOCR支持超过80种语言的识别,包括英语、中文(简繁)、阿拉伯文、日文等,并且该库在不断更新中,未来会支持更多的语言。

1.步骤一:安装 EasyOCR库

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple easyocr

注意:EasyOCR库比较大,一定要更改为国内源,要不然等到天荒地老!

pic_008.png

2.步骤二:使用方法介绍

EasyOCR的用法非常简单,分为三步:

1.创建识别对象;2.读取并识别图像;3.导出文本。

3.步骤三:实例使用参考

参考源码:

# 导入easyocr
import easyocr
# 创建reader对象
reader = easyocr.Reader(['ch_sim','en']) 
# 读取图像
result = reader.readtext('test.jpg')
# 结果
print(result)

可惜未调试成功,暂不清楚问题所在,贴出问题所在,知晓的老哥可以指点一二!

pic_009.png

报错信息:

E:\Python\venv\Scripts\python.exe E:/Python/twsb/ff2.py
E:\Python\venv\lib\site-packages\skimage\io\manage_plugins.py:23: UserWarning: Your installed pillow version is < 7.1.0. Several security issues (CVE-2020-11538, CVE-2020-10379, CVE-2020-10994, CVE-2020-10177) have been fixed in pillow 7.1.0 or higher. We recommend to upgrade this library.
  from .collection import imread_collection_wrapper
CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.
Downloading detection model, please wait
Traceback (most recent call last):
  File "E:/Python/twsb/ff2.py", line 4, in <module>
    reader = easyocr.Reader(['ch_sim','en'])
  File "E:\Python\venv\lib\site-packages\easyocr\easyocr.py", line 170, in __init__
    urllib.request.urlretrieve(model_url['detector'][0] , DETECTOR_PATH)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 247, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 531, in open
    response = meth(req, response)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 640, in http_response
    response = self.parent.error(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 569, in error
    return self._call_chain(*args)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 502, in _call_chain
    result = func(*args)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

Process finished with exit code 1

方法二:ORC(tesseract-ocr)识别

安装pytesseract库,必须先安装其依赖的PIL及tesseract-ocr,其中PIL为图像处理库,而后面的tesseract-ocr则为google的ocr识别引擎。

1.步骤一:配置ORC本地环境

安装tesseract-ocr,这个没有什么好说的,下载好程序,点击下一步,安装步骤安装即可!

pic_010.png

但是需要配置系统环境变量,或者在调用程序的时候需要注明工具的路径,即安装后tesseract.exe的路径!

pic_011.png

关于配置系统环境变量可自行百度配置,这里本渣渣没有配置,直接注明应用路径地址:

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

注意:

下载chi_sim.traindata字库。要有这个才能识别中文。

下好后,放到Tesseract-OCR项目的tessdata文件夹里面。

pic_012.png

为了便于大家测试使用,这里本渣渣打包了工具程序包!


关注本渣渣微信公众号:二爷记

pic_013.jpg

后台回复 ocr

即可获取tesseract-ocr及中文识别库(本渣渣系统是win7 64位,亲测可用)!


2.步骤二:安装库

安装pytesseract(换源)和安装PIL(换源)

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pytesseract

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pillow

3.步骤三:调用接口识别图片文字信息

参考源码:

# 图像识别初识
#author:微信:huguo00289
#微信公众号:二爷记
# -*- coding: utf-8 -*-

import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = r'D:/Program Files/Tesseract-OCR/tesseract.exe'
image = Image.open('cs.png')
#code = pytesseract.image_to_string(image)
code = pytesseract.image_to_string(image, lang="chi_sim+eng")
print(code)

本方法对于识别一些简单纯净的中文、数字、字母和标点符号的效果还是不错的,如果是经过处理的图片,比如验证码等图片的识别,需要借助jTessBoxEditor训练字库才能提高识别的准确率哦!


方法三:调用百度官方OCR接口

调用百度官方OCR接口,付费,识别率高!

官方介绍:多场景、多语种、高精度的文字检测与识别服务,多项ICDAR指标居世界第一;广泛适用于远程身份认证、财税报销、文档电子化等场景,为企业降本增效;提供稳定易用的在线API、离线SDK、软件部署包多种服务形式,最高可享每天50000次免费调用。

pic_019.png

官方调用接口参考源码:

1.获取Access Token权限

# encoding:utf-8
# 获取Access Token权限
import requests 

# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'
response = requests.get(host)
if response:
    print(response.json())


2.调用接口识别图片文字信息

# encoding:utf-8

import requests
import base64

'''
通用文字识别
'''

request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
# 二进制方式打开图片文件
f = open('[本地文件]', 'rb')
img = base64.b64encode(f.read())

params = {"image":img}
access_token = '[调用鉴权接口获取的token]'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
    print (response.json())

本渣渣亲自上手撸一发,仅供参考代码:

# encoding:utf-8
#author:微信:huguo00289
#微信公众号:二爷记
#百度通用文字识别(标准版)
#https://cloud.baidu.com/doc/OCR/s/zk3h7xz52
import requests
import base64

def bdocr(AK,SK,imgname):
    host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={AK}&client_secret={SK}'
    response = requests.get(host)
    access_token=response.json()['access_token']

    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    # 二进制方式打开图片文件
    f = open(imgname, 'rb')
    img = base64.b64encode(f.read())

    params = {"image":img}

    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    datas_json=response.json()['words_result']
    for data_json in datas_json:
        data=data_json['words']
        print(data)



if __name__=='__main__':
    AK="API Key"   #client_id 为官网获取的AK
    SK="Secret Key"   #client_secret 为官网获取的SK
    imgname='cs.png'  #图片路径名
    bdocr(AK, SK,imgname)

pic_020.gif

最后,我们来实现批量识别图片文字信息的工具,应用python也是非常容易实现的,就是读取文件夹里的所有图片,然后通过循环遍历来反复调用接口即可获取到所有图片的文字信息,这里接口,本渣渣直接调用的是百度的OCR接口,推荐使用。

pic_021.gif

附上参考源码,仅供参考使用:

# encoding:utf-8
#author:微信:huguo00289
#微信公众号:二爷记
#批量百度通用文字识别(标准版)
#https://cloud.baidu.com/doc/OCR/s/zk3h7xz52
import requests
import base64
import os


#读取文件夹里所有的图片
def read_imgs(path):
    imgs = []
    for filename in os.listdir(path):
        img = f'{path}\\{filename}'
        if 'jpg' in str(os.path.splitext(img)[-1]):
            print(img)
            imgs.append(img)
        if 'png' in str(os.path.splitext(img)[-1]):
            print(img)
            imgs.append(img)


    print(f'共有 {len(imgs)} 张图片!')
    return imgs


#获取百度access_token权限
def get_access_token(AK, SK):
    host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={AK}&client_secret={SK}'
    response = requests.get(host)
    access_token=response.json()['access_token']

    return access_token


#调用百度ocr接口识别图文文字信息
def bdocr(access_token,imgname):
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    # 二进制方式打开图片文件
    f = open(imgname, 'rb')
    img = base64.b64encode(f.read())

    params = {"image":img}

    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    datas_json=response.json()['words_result']
    for data_json in datas_json:
        data=data_json['words']
        print(data)





if __name__=='__main__':
    AK="API Key"   #client_id 为官网获取的AK
    SK="Secret Key"   #client_secret 为官网获取的SK
    path=r'path'   #文件夹路径
    imgs=read_imgs(path)
    access_token=get_access_token(AK, SK)
    for img in imgs:
        print(f"正在识别:{img}")
        bdocr(access_token,img)

总结

1.一般的验证码识别,大小写字母,数字,中文混合验证码都可以考虑使用,没错可实现论坛回帖,发帖验证码自动打码的功能,比如应用百度ocr接口,可自行处理豆瓣回帖自动打码功能。

2.当然还有就是seo内容的来源问题解决,比如抄书神器,把图片文字信息内容整合为你网站的纯干货文章内容,当然你需要注意规避版权!

3.可以自行整合为exe工具,或者是网页在线工具,方便他人使用 ,也就是本渣渣这里介绍的方法二的网上在线图文识别工具,用来引流,做一个工具类型的网站。


参考来源:

1.如何提取图片中的文字?这款Python 库 4行代码搞定!

https://mp.weixin.qq.com/s/RpZzYg3cMynWHVWQT3fk1g


2.Python 图片文字识别

https://www.cnblogs.com/zhurong/p/11685013.html


3.pillow、pytesseract-ocr、pytesseract的安装和中文的识别

https://blog.csdn.net/qq_38190041/article/details/102903464


4.python库学习 - pytesseract 识别图片中文字

https://www.jianshu.com/p/40ed39f3efbd


5.通用文字识别(标准版)

https://cloud.baidu.com/doc/OCR/s/zk3h7xz52