批量为图片添加去除后缀的文件名标签

Page content

   批量为图片添加去除后缀的文件名标签。

   批量为图片添加去除后缀的文件名标签,支持自定义文字大小、位置、颜色及背景透明度,兼容多种图片格式,能指定输出目录,适用于快速标注图片便于识别。。

from PIL import Image, ImageDraw, ImageFont
import os
import sys

def add_filename_to_image(image_path, text_ratio=0.05, output_dir=None):
    """
    给图片添加去除后缀的文件名
    
    参数:
    image_path: 图片路径
    text_ratio: 文字大小与图片高度的比例,默认为0.05
    output_dir: 输出目录,默认为原图片所在目录
    """
    try:
        # 打开图片
        with Image.open(image_path) as img:
            # 获取图片文件名并去除后缀
            filename = os.path.basename(image_path)
            name_without_ext = os.path.splitext(filename)[0]
            
            # 创建可绘制对象
            draw = ImageDraw.Draw(img)
            
            # 获取图片尺寸
            width, height = img.size
            
            # 根据比例计算文字大小
            font_size = int(height * text_ratio)
            
            # 尝试加载系统字体,若失败则使用默认字体
            try:
                # 尝试使用系统字体(可能需要根据操作系统调整)
                if sys.platform.startswith('win'):
                    font = ImageFont.truetype("arial.ttf", font_size)
                elif sys.platform.startswith('darwin'):  # macOS
                    font = ImageFont.truetype("C:\Windows\Fonts\simsun.ttc", font_size)
                else:  # Linux
                    font = ImageFont.truetype("C:\Windows\Fonts\msyhl.ttc", font_size)
            except:
                # 若无法加载指定字体,使用默认字体
                font = ImageFont.load_default()
                print(f"警告: 无法加载指定字体,使用默认字体。图片: {filename}")
            
            # 计算文字位置(左上角,留出一些边距)
            margin = int(font_size * 0.5)
            x, y = margin, margin
            
            # 添加文字,使用半透明黑色背景增加可读性
            text_bbox = draw.textbbox((x, y), name_without_ext, font=font)
            draw.rectangle([text_bbox[0]-2, text_bbox[1]-2, text_bbox[2]+2, text_bbox[3]+2], 
                          fill=(0, 0, 0, 128))  # 半透明黑色背景
            draw.text((x, y), name_without_ext, font=font, fill=(255, 0, 0))  # 白色文字
            
            # 确定输出路径
            if output_dir is None:
                output_dir = os.path.dirname(image_path)
            
            # 创建输出目录(如果不存在)
            os.makedirs(output_dir, exist_ok=True)
            
            # 保存处理后的图片
            output_filename = f"labeled_{filename}"
            output_path = os.path.join(output_dir, output_filename)
            img.save(output_path)
            
            print(f"已处理并保存: {output_path}")
            return output_path
            
    except Exception as e:
        print(f"处理图片 {image_path} 时出错: {str(e)}")
        return None

def process_images_in_directory(directory, text_ratio=0.05, output_dir=None):
    """处理目录中的所有图片"""
    # 支持的图片格式
    image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff')
    
    # 遍历目录中的所有文件
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        
        # 检查是否为图片文件
        if os.path.isfile(file_path) and filename.lower().endswith(image_extensions):
            add_filename_to_image(file_path, text_ratio, output_dir)

if __name__ == "__main__":
    # 示例用法
    # 处理单个图片
    # add_filename_to_image("example.jpg", text_ratio=0.05)
    
    # 处理目录中的所有图片
    process_images_in_directory(r"C:\Users\Administrator\Desktop\新建文件夹 (3)", text_ratio=0.05, output_dir="./labeled_images")