使用python基于计算机视觉旋转文本图片

前言:我有一些文本图片要进行文字识别,但进行文字识别之前发现有些图片被旋转了一定角度,我需要将这些图片旋转到正常的角度。本方案只用于旋转图片,不用于旋转图片中的字体,旋转的角度有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)

三、效果展示

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值