📅  最后修改于: 2023-12-03 15:24:00.482000             🧑  作者: Mango
近年来,OCR 技术发展迅速,应用越来越广泛。本文将介绍如何使用 Python 语言提取图片中的文字。
开发环境:Python 3.0以上版本 + Tesseract OCR API
需要用到的 Python 库:numpy
,pytesseract
,opencv-python
Tesseract OCR 是一款免费开源的 OCR 引擎,支持超过100种语言的识别。我们可以先从 Tesseract OCR 官网下载并安装。
pip install numpy
pip install pytesseract
pip install opencv-python
import cv2
import numpy as np
import pytesseract
# 读入图像
img = cv2.imread('image.png')
# 转为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯滤波去噪
blur = cv2.GaussianBlur(gray, (3, 3), 0)
# 图像二值化
ret, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 进行腐蚀和膨胀
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
erode = cv2.erode(binary, kernel)
dilate = cv2.dilate(erode, kernel)
# 定位文本区域
_, contours, hierarchy = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rects = [cv2.boundingRect(cnt) for cnt in contours]
for rect in rects:
x, y, w, h = rect
if w < 50 or h < 10:
continue
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
roi = dilate[y:y + h, x:x + w]
roi = cv2.resize(roi, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
text = pytesseract.image_to_string(roi, lang='eng', config='--psm 7')
print('文本:', text)
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)
ret, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
erode = cv2.erode(binary, kernel)
dilate = cv2.dilate(erode, kernel)
_, contours, hierarchy = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rects = [cv2.boundingRect(cnt) for cnt in contours]
for rect in rects:
x, y, w, h = rect
if w < 50 or h < 10:
continue
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
roi = dilate[y:y + h, x:x + w]
roi = cv2.resize(roi, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
text = pytesseract.image_to_string(roi, lang='eng', config='--psm 7')
print('文本:', text)
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
通过本文的学习,我们可以看到,使用 Python 实现 OCR 技术并不难。本文虽然只提供了基础的代码,但是可以通过不断地尝试,慢慢提高程序的识别率。