使用paddle OCR对带文字的图片转正

使用python+OCR实现图片矫正

python 复制代码
import cv2
import numpy as np
from paddleocr import PaddleOCR


# 设定模型路径
paddleocr = PaddleOCR(
		      cls_model_dir='D:/paddle OCR/ch_ppocr_mobile_v2.0_cls_slim_infer',
                      det_model_dir='D:/paddle OCR/ch_PP-OCRv4_det_infer',
                      rec_model_dir='D:/paddle OCR/ch_PP-OCRv4_rec_infer') # 推理模型路径
# img = cv2.imread(r'D:\LabelAOI\source\Test\CM\6.jpg')  # 打开需要识别的图片
img = cv2.imread(r'D:\LabelAOI\source\Test\crops\26463274Q0041-W2N0CV02C922064_20260207003954_L_main_CAM_basler_UPC_CAM114.jpg')  # 打开需要识别的图片
# img = cv2.resize(image, (300,500))
#img = cv2.imread(r'.\UPC_CAM94.jpg')  # 打开需要识别的图片
result = paddleocr.ocr(img)

# 获取文字内容最长的框
max_text_length = 0
max_text_index = 0

for i, (points, (text, confidence)) in enumerate(result[0]):
    current_length = len(text.strip())
    if current_length > max_text_length and current_length > 0:
        max_text_length = current_length
        max_text_index = i
# 获取最长文本的框坐标(转换为Python原生整数)
points, (text, confidence) = result[0][max_text_index]
points = np.array(points, dtype=np.int32)  # 先转numpy整数
# 从numpy数组中提取元素,并转换为Python原生int类型
rot_center_x = int(points[0][0].item())  # .item()将numpy类型转为Python类型
rot_center_y = int(points[0][1].item())
rot_center = (rot_center_x, rot_center_y)  # 确保是纯Python整数元组
# 计算旋转角度
dx = points[1][0] - points[0][0]
dy = points[1][1] - points[0][1]
angle = np.arctan2(dy, dx) * 180 / np.pi  # 弧度转角度
# 生成旋转矩阵(此时rot_center为Python int元组,符合OpenCV要求)
M = cv2.getRotationMatrix2D(rot_center, angle, 1.0)
rotated_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
# # 绘制结
# cv2.polylines(rotated_img, [points], True, (0, 255, 0), 2)
# confidence_percentage = int(confidence * 100)
# cv2.putText(
#     rotated_img, f"{text} ({confidence_percentage}%)",
#     (points[0][0], points[0][1] - 10),
#     cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2
# )
# cv2.putText(
#     rotated_img, f"Angle: {angle:.2f}°",
#     (points[0][0], points[0][1] - 30),
#     cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2
# )

cv2.imwrite("D:\paddle OCR\mm.png", rotated_img)
cv2.imshow('Longest Text Region', rotated_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

效果如下:

相关推荐
学测绘的小杨11 小时前
CompassFusion:一个从 GNSS 到 GNSS/INS 组合导航的独立工程包
python
zzzzzz31018 小时前
当产品经理说这个很简单:我用Python自动化处理奇葩需求的实战指南
python·pycharm·产品经理
雪隐18 小时前
个人电脑玩AI-06让5060 Ti给你打工——不光能画画,Qwen3-TTS还能学人说话,连我老板都信了!
人工智能·后端·python
兵慌码乱1 天前
面向桌面端的资产管理系统分层架构设计与核心模块实现
python·系统架构·sqlite·pyqt5·数据库设计·桌面应用开发·mvc架构
hboot1 天前
AI工程师第三课 - 机器学习基础
python·scikit-learn·kaggle
顾林海1 天前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱2 天前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽2 天前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码2 天前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱2 天前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理