前言:我有一些文本图片要进行文字识别,但进行文字识别之前发现有些图片被旋转了一定角度,我需要将这些图片旋转到正常的角度。本方案只用于旋转图片,不用于旋转图片中的字体,旋转的角度有90度,
一、安装相关的依赖包
1、安装pytesseract
pip install pytesseract -i https://pypi.tuna.tsinghua.edu.cn/simple/
2、安装完pytesseract后下载pytesseract-ocr,下载路径为Index of /tesseract
选择适合自己电脑的版本安装即可,安装过程中全部点击“下一步”即可安装。
3、修改pytesseract.py文件
记住自己pytesseract-ocr的安装路径,然后修改第一步安装的pytesseract中的pytesseract.py文件。
4、安装cv2
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
二、编写旋转文本图片的代码
话不多说,直接使用即可。
import cv2
import pytesseract
import os
def detect_text_orientation(image_path):
# 读取图片
image = cv2.imread(image_path)
# 灰度处理
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
text = 0
try:
# 获取图片文字方向信息
text = pytesseract.image_to_osd(gray)
print(text,653721)
except pytesseract.pytesseract.TesseractError as e:
# 处理异常,文字太少或无法识别的情况则跳过
print(f"Error processing image: {e}")
if text == 0:
orientation = 0
else:
# 旋转度数获取
lines = text.split('\n')
for line in lines:
if line.startswith('Rotate'):
orientation = int(line.split(':')[-1].strip())
break
else:
orientation = 0
return orientation
def rotate_and_save_images_in_folder(folder_path):
for filename in os.listdir(folder_path):
# 图片类别
if filename.endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')):
image_path = os.path.join(folder_path, filename)
print(f" 正在处理: {image_path}")
#
if os.path.isfile(image_path):
# 获取文本方向信息
text_orientation = detect_text_orientation(image_path)
# 读取图片
image = cv2.imread(image_path)
# 根据图片方向旋转图片
if text_orientation == 90:
rotated = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
elif text_orientation == 270:
rotated = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
elif text_orientation == 180:
rotated = cv2.rotate(image, cv2.ROTATE_180)
else:
rotated = image
# 保存旋转后的图片
cv2.imwrite(image_path, rotated)
if __name__ == "__main__":
# 选择图片路径,将会遍历该路径下的所有图片
folder_path = "C:/Users/Hello/Desktop/data2"
rotate_and_save_images_in_folder(folder_path)