一、图片变换
0、导入模块
导入相关函数,遇到报错的话,直接pip install 函数名。
import numpy as np import argparse import cv2
参数初始化
ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image to be scanned") args = vars(ap.parse_args())
Parameters:
--image images\page.jpg
1、重写resize函数
def resize(image, width=None, height=None, inter=cv2.INTER_AREA): dim = None (h, w) = image.shape[:2] if width is None and height is None: return image if width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) resized = cv2.resize(image, dim, interpolation=inter) return resized
2、预处理
读取图片后进行重置大小,并计算缩放倍数;进行灰度化、高斯滤波以及Canny轮廓提取
image = cv2.imread(args["image"]) ratio = image.shape[0] / 500.0 orig = image.copy() image = resize(orig, height = 500) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, 75, 200)
3、边缘检测
检测轮廓并排序,遍历轮廓。
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0]# 轮廓检测 cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]#保留前5个轮廓 # 遍历轮廓 for c in cnts: # 计算轮廓近似 peri = cv2.arcLength(c, True)# 计算轮廓长度,C表示输入的点集,True表示轮廓是封闭的 #(C表示输入的点集,epslion判断点到相对应的line segment 的距离的阈值,曲线是否闭合的标志位) approx = cv2.approxPolyDP(c, 0.02 * peri, True) # 4个点的时候就拿出来 if len(approx) == 4: screenCnt = approx break
4、透视变换
画出近似轮廓,透视变换,二值处理
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2) warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)#透视变换 # 二值处理 warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) ref = cv2.threshold(warped, 100, 255, cv2.THRESH_BINARY)[1] cv2.imwrite('scan.jpg', ref)
二、OCR识别
0、安装tesseract-ocr
链接: 下载
在环境变量、系统变量的Path里面添加安装路径,例如:E:\Program Files (x86)\Tesseract-OCR
tesseract -v#打开命令行,进行测试 tesseract XXX.png result#得到结果 pip install pytesseract#安装依赖包
打开python安装路径里面的python文件,例如C:\ProgramData\Anaconda3\Lib\site-packages\pytesseract\pytesseract.py
将tesseract_cmd 修改为绝对路径即可,例如:tesseract_cmd = ‘C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'
1、导入模块
from PIL import Image import pytesseract import cv2 import os
2、预处理
读取图片、灰度化、滤波
image = cv2.imread('scan.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 3)
3、输出结果
filename = "{}.png".format(os.getpid()) cv2.imwrite(filename, gray) text = pytesseract.image_to_string(Image.open(filename)) print(text) os.remove(filename)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Opencv 图片的OCR识别的实战示例”评论...
更新日志
2024年07月03日
2024年07月03日
- 原画壁纸及美图第255期,无水印可自取
- 群星.1991-宝丽金冬日浓情【宝丽金】【WAV+CUE】
- 胡杨林.2006-香水有毒【太格印象】【WAV+CUE】
- 陈晓东.2002-从未忘记2CD【环球】【WAV+CUE】
- 绝区零珂蕾妲阵容怎么搭配好 珂蕾妲队伍搭配攻略
- 绝区零暴击鸣徽有哪些 绝区零暴击鸣徽效果介绍
- 魔兽世界奥格瑞玛法师训练师在哪 奥格瑞玛法师训练师位置介绍
- 《艾尔登法环》dlc带电祷告位置介绍
- 《幻兽帕鲁》泰锋boss坐标位置介绍
- 《山河旅探》6月份更新内容介绍
- 群星.2012《高雄国际Hi-End音响大展纪念发烧金碟(最响宣言)》[WAV分轨].
- 黄宣2021-Beanstalk[否极泰来][WAV+CUE]
- 康康1999-催泪[阿尔法][WAV+CUE]
- 人总有崩溃的时候:你玩过哪些能治愈人心的游戏?
- SteamDeck新增最热玩榜单:综合衡量玩家数和时长