import cv2import pytesseractpytesseractpytesseracttesseract_cmd = rDtesseract-ocrtesseractexeimg = cv2imreadCUsersjiangaoDesktop1jpg# 将彩色图像转换为灰度图像gray = cv2cvtColorimg cv2COLOR_BGR2GRAY# 对图像进行二值化处理thr
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'D:\tesseract-ocr\tesseract.exe'
img = cv2.imread('C:/Users/jian.gao/Desktop/1.jpg')
缩小图片尺寸,去除噪声
img = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
将彩色图像转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
对图像进行二值化处理
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
对图像进行膨胀操作,填充空洞
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) dilate = cv2.dilate(thresh, kernel, iterations=1)
对图像进行腐蚀操作,去除噪声
erode = cv2.erode(dilate, kernel, iterations=1)
识别图像中的文字
text = pytesseract.image_to_string(erode, lang='chi_sim')
print(text)
显示图片和二值化后的图片
cv2.imshow('image', img) cv2.imshow('erode', erode) cv2.waitKey(0) cv2.destroyAllWindows()
原文地址: https://www.cveoy.top/t/topic/7WK 著作权归作者所有。请勿转载和采集!