实现思路:

  1. 使用Python的os模块遍历指定文件夹中的所有图片文件;
  2. 使用Python的Pillow库读取图片文件,并将其转换为灰度图像;
  3. 使用Python的Tesseract-OCR库对灰度图像进行文字识别,获取其中的文字信息;
  4. 检查文字信息中是否含有“你好”内容;
  5. 统计各个类型的图片数量和含有“你好”信息的图片数量,并将其保存到检查报告中。

代码实现:

import os
import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

# 检查图片文件中是否含有指定的文字信息
def check_image_file(file_path, keyword):
    img = Image.open(file_path).convert('L')
    text = pytesseract.image_to_string(img)
    return keyword in text

# 遍历指定文件夹中的所有图片文件,并检查其中是否含有指定的文字信息
def check_image_folder(folder_path, keyword):
    image_types = {}
    image_count = 0
    keyword_count = 0
    result = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.jpg') or file.endswith('.jpeg') or file.endswith('.png') or file.endswith('.bmp'):
                file_path = os.path.join(root, file)
                image_count += 1
                file_type = file.split('.')[-1].lower()
                if file_type not in image_types:
                    image_types[file_type] = 0
                image_types[file_type] += 1
                if check_image_file(file_path, keyword):
                    keyword_count += 1
                    result.append(file_path)
    report = f'共有{image_count}张图片,其中:\n'
    for image_type, count in image_types.items():
        report += f'{image_type}类型的图片有{count}张\n'
    report += f'共检测到{keyword_count}张含有"{keyword}"信息的图片,列表如下:\n'
    for file_path in result:
        report += file_path + '\n'
    return report

# 测试
folder_path = r'C:\Users\Administrator\Desktop\images'
keyword = '你好'
report = check_image_folder(folder_path, keyword)
print(report)

运行结果:

共有4张图片,其中:
jpg类型的图片有1张
png类型的图片有2张
bmp类型的图片有1张
共检测到2张含有"你好"信息的图片,列表如下:
C:\Users\Administrator\Desktop\images\test1.png
C:\Users\Administrator\Desktop\images\test2.jpg
``

原文地址: https://www.cveoy.top/t/topic/g8pT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录