当图像已经正面朝上时,将图像旋转 90° 4 次的 OCR 代码会失败

问题描述 投票:0回答:1

我已经使用 PyTesseract 编写了 Python 代码,从可能旋转的图像中提取文本。它通过尝试从基本图像中获取文本,然后将其旋转 90 度三次并比较从每个图像中检测到的文本的置信度来实现此目的。然后它会选择置信度得分最高的图像并打印文本。

当我给它已经横向或上下旋转的图像时,它可以工作(正确提取文本)。但是当我给它正面朝上的图像时,它无法弄清楚文本是什么。出了什么问题?

import pytesseract
import cv2

myconfig = r"--psm 6 --oem 3"

# Replace with your image file path
img = cv2.imread("lib\math\one (un).jpg")

# Create a function to find the best rotation angle
def find_best_rotation(image):
    confidences = []
    for angle in [0, 90, 180, 270]:
        rotated_image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE if angle == 90 else cv2.ROTATE_90_COUNTERCLOCKWISE if angle == 270 else cv2.ROTATE_180)
        text = pytesseract.image_to_string(rotated_image, config=myconfig)
        confidences.append((angle, len(text.strip())))

    best_rotation, _ = max(confidences, key=lambda x: x[1])
    return best_rotation

best_rotation = find_best_rotation(img)

# Rotate the image to the best rotation
best_rotated_image = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE if best_rotation == 90 else cv2.ROTATE_90_COUNTERCLOCKWISE if best_rotation == 270 else cv2.ROTATE_180)

text = pytesseract.image_to_string(best_rotated_image, config=myconfig)

print(f"Best rotation angle: {best_rotation} degrees")
print("Text extracted from the image:")
print(text)
python python-tesseract
1个回答
0
投票

想想这段代码的作用:

for angle in [0, 90, 180, 270]:
    rotated_image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE if angle == 90 else cv2.ROTATE_90_COUNTERCLOCKWISE if angle == 270 else cv2.ROTATE_180)
  • 如果
    angle
    90
    ,则图像顺时针旋转 90°。
  • 如果
    angle
    270
    ,则图像逆时针旋转 90°。
  • 否则,图像将旋转 180°。

这意味着即使

angle
0
,你仍然要把它颠倒过来。这意味着您实际上从未以原始方向分析图像。因此,如果您提供的图像已经是正面朝上,OCR 就会失败。

既然你从来没有真正使用过数字角度,为什么不使用这样的东西呢?

rotation_codes = [
    None,
    cv2.ROTATE_90_CLOCKWISE,
    cv2.ROTATE_90_COUNTERCLOCKWISE,
    cv2.ROTATE_180
]

for code in rotation_codes:
    rotated_image = cv2.rotate(image, code) if code is not None else image
© www.soinside.com 2019 - 2024. All rights reserved.