最后简单根据x,y做一些数据整理
这里我为了图方便直接约10
data = {}
def insert_lesson_data(x, y, text):
pos = int(int(x / 10) * 10)
if pos not in data:
data[pos] = []
data[pos].append((y, text))
打印之前记得排序一下
for x in sorted(data.keys()):
print(f"{x}:")
data[x].sort(key=lambda item: item[0])
for y, text in data[x]:
print(f"x: {x} y: {y}, text: {text}")
效果图
完整代码
import logging
import cv2
import numpy as np
from paddleocr import PaddleOCR
logging.disable(logging.DEBUG)
data = {}
def insert_lesson_data(x, y, text):
pos = int(int(x / 10) * 10)
if pos not in data:
data[pos] = []
data[pos].append((y, text))
ocr = PaddleOCR(use_angle_cls=True, lang="ch")
originImage = cv2.imread("test.png")
image = cv2.cvtColor(originImage, cv2.COLOR_BGR2GRAY)
denoised_image = cv2.fastNlMeansDenoising(image, None, 30, 7, 21)
ret, thresh = cv2.threshold(denoised_image, 220, 255, cv2.THRESH_TRUNC)
_, binary = cv2.threshold(thresh, 128, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(originImage, contours, -1, (0,0, 255), 2) 画全部
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
x, y, w, h = cv2.boundingRect(contours[i])
if area > 500 and w >= 100 and w <= 888:
top_left = (x, y)
bottom_right = (x + w, y + h)
roi = thresh[y : y + h, x : x + w]
result = ocr.ocr(roi, cls=False)
text = ""
for line in result:
if line is not None:
for word_info in line:
text += word_info[1][0]
cv2.rectangle(originImage, top_left, bottom_right, (0, 0, 255), 2)
insert_lesson_data(x, y, text)
for x in sorted(data.keys()):
print(f"{x}:")
data[x].sort(key=lambda item: item[0])
for y, text in data[x]:
print(f"x: {x} y: {y}, text: {text}")
cv2.imshow("originImage", originImage)
cv2.waitKey(0)
cv2.destroyAllWindows()