使用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()

效果如下:

相关推荐
墨染青竹梦悠然2 小时前
基于Django+vue的单词学习平台
前端·vue.js·后端·python·django·毕业设计·毕设
喵手2 小时前
Python爬虫实战:实现 Playwright 的动态名言“瀑布流”采集器,采集名言内容、作者及出处等信息(附 JSON 格式数据导出)!
爬虫·python·爬虫实战·playwright·零基础python爬虫教学·构建动态名言瀑布流采集器·采集数据json导出
喵手2 小时前
Python爬虫实战:全国旅游景区名录智能采集系统 - 构建文旅大数据的基石(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·全国旅游景区名采集系统·文旅大数据·采集旅游景区sqlite存储
E_ICEBLUE4 小时前
Python 实现 PDF 表单域的自动化创建与智能填充
python·pdf·自动化·表单域
YJlio10 小时前
1.7 通过 Sysinternals Live 在线运行工具:不下载也能用的“云端工具箱”
c语言·网络·python·数码相机·ios·django·iphone
l1t10 小时前
在wsl的python 3.14.3容器中使用databend包
开发语言·数据库·python·databend
山塘小鱼儿11 小时前
本地Ollama+Agent+LangGraph+LangSmith运行
python·langchain·ollama·langgraph·langsimth
码说AI12 小时前
python快速绘制走势图对比曲线
开发语言·python