在我们爬取数据时,可能遇见想要获取数字,但是网站数字是以图片的形式展现的,所以我们要使用一些方法进行图片识别,在之前我们提及用超级鹰来识别图片,这里我们再来介绍几种方式对于这种较为明显的图片进行识别,当然对于一些图片可以进行二值化处理后进行识别。
例如识别这样的图片数据:
要得到173 0384 3736结果
- # 需要的两个库:
- from PIL import Image
- import pytesseract
-
- # 将图片以二进制形式储存在img变量中
- # 由于图片是本地图片所以使用open方式读取数据
- # "phone_number.jpg"是上图路径
- # 在使用爬虫我们通常是这样的:
- # img = requests.get("图片的url").content
- img=open("phone_number.jpg",mode="rb").read()
-
- # 使用io.BytesIO方式打开图片字节流,得到图片对象
- img_data = Image.open(io.BytesIO(img))
- # 也可以直接img_data = Image.open(r"phone_number.jpg")
-
- # pytesseract.image_to_string将从图片对象的img_data中识别并转化为字符串
- res = pytesseract.image_to_string(img_data)
- print(res) # 输出:173 0384 3736
-
当然对于PIL比较容易安装,但是对于pytesseract不简单,使用时可能会报错:
- pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your PATH. See README file for more information.
-
那么如何解决呢?
戳它!!!
于是对于之前提到的古诗文网验证码识别就有了新方法
为了提高识别率我们进行图片二极化处理
这里是图片格式为png的代码:
- import cv2
- from PIL import Image
- import pytesseract
-
- # 为了方便使用,给大家分装成了函数
- def ver_code(img_path):
- img = cv2.imread(img_path, 0)
- ret, new_image = cv2.threshold(img, 120, 220,cv2.THRESH_BINARY)
- cv2.imwrite("./pic.png", new_image)
- res = pytesseract.image_to_string(Image.open('pic.png'))
- return res
-
- ver_code('phone_number.jpg')
- # 传入验证码地址,返回结果为识别的字符串
-
实例:
收到小伙伴反馈,现在图片改成了gif
能难到我们吗?
首先导入库pillow
- import cv2
- from PIL import Image
- import pytesseract
-
-
- # 为了方便使用,给大家分装成了函数
- def ver_code(img_path):
- im = Image.open(img_path)
- pngDir = img_path[:-4]+'.png'
- try:
- im.save(pngDir)
- except EOFError:
- pass
- img = cv2.imread(pngDir, 0)
- ret, new_image = cv2.threshold(img, 120, 220, cv2.THRESH_BINARY)
- cv2.imwrite(pngDir, new_image)
- res = pytesseract.image_to_string(Image.open(pngDir))
- return res
-
-
- ver_code('图片名.gif')
- # 返回字符串
-
另外还有一个比较简单的库ddddocr:返回的就是验证码的字符串
- import ddddocr
- fp = open("图片地址","rb")
- img_bytes = fp.read()
- fp.close()
- res = ddddocr.DdddOcr().classification(img_bytes)
- print(res)
-