PyTesseract旋转识别代码处理正向图片时失效的问题排查
问题原因与解决方案
问题根源
你的代码在处理**0度(原图)**时存在逻辑错误:
在find_best_rotation函数的循环中,当angle == 0时,嵌套三元表达式的最终分支会执行cv2.ROTATE_180——也就是说你并没有直接用原图识别文本,反而把正向图片旋转180度后再提取内容。这会导致0度对应的识别结果是倒置状态的无效文本(长度极短甚至为空),最终函数会错误地选择其他旋转角度;即使偶然选到0度,后续旋转时也会把原图转成180度,自然无法识别正向图片的内容。
错误代码片段:
rotated_image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE if angle == 90 else cv2.ROTATE_90_COUNTERCLOCKWISE if angle == 270 else cv2.ROTATE_180)
修复方案
修改旋转逻辑,明确0度时直接使用原图,不做旋转操作:
修复后的完整代码
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]: # 明确各角度对应的处理逻辑 if angle == 0: rotated_image = image.copy() elif angle == 90: rotated_image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE) elif angle == 180: rotated_image = cv2.rotate(image, cv2.ROTATE_180) elif angle == 270: rotated_image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE) 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 if best_rotation == 0: best_rotated_image = img.copy() elif best_rotation == 90: best_rotated_image = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) elif best_rotation == 180: best_rotated_image = cv2.rotate(img, cv2.ROTATE_180) elif best_rotation == 270: best_rotated_image = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE) 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)
优化说明
- 把嵌套三元表达式拆分为清晰的if-elif分支,避免逻辑歧义,也便于后续维护
- 0度时直接复制原图,保证用正向状态识别文本
- 后续生成最佳旋转图片时,同样对0度做单独处理,避免不必要的旋转操作
额外建议
- 如果图片存在非90度倍数的倾斜,可以考虑加入倾斜校正逻辑(比如通过霍夫变换检测文本行角度)
- 可尝试调整Tesseract的
--psm参数,比如用--psm 3(默认自动分页)适配更多场景
内容的提问来源于stack exchange,提问作者Mohamad Bdeir
相关产品推荐
相关产品推荐

