根据bounding box坐标框绘制mask

根据bounding box坐标框绘制mask

import os
from PIL import Image, ImageDraw

# 定义图像和标注文件夹路径
image_folder_path = r'F:\Liang\Datasets\Text_dataset\Tampered-IC13\train_img'
annotation_folder_path = r'F:\Liang\Datasets\Text_dataset\Tampered-IC13\train_gt'

# 获取图像文件夹中的所有文件
image_files = [f for f in os.listdir(image_folder_path) if os.path.isfile(os.path.join(image_folder_path, f))]

# 遍历图像文件
for image_file in image_files:
    # 构建图像和标注文件的完整路径
    image_path = os.path.join(image_folder_path, image_file)
    annotation_file = os.path.splitext(image_file)[0] + '.txt'
    annotation_path = os.path.join(annotation_folder_path, annotation_file)

    # 打开图像文件
    original_image = Image.open(image_path)
    width, height = original_image.size

    # 创建一个新的黑色图像作为mask
    mask_image = Image.new('L', (width, height), 0)
    draw = ImageDraw.Draw(mask_image)

    # 读取标注文件并绘制bounding boxes
    with open(annotation_path, 'r') as file:
        for line in file:
            coordinates = list(map(int, line.strip().split(',')))
            x1, y1, x2, y2, _ = coordinates
            draw.rectangle([x1, y1, x2, y2], fill=255, outline=255)

    # # 使用mask图像裁剪原始图像
    # masked_image = Image.new('RGB', (width, height), 'black')
    # masked_image.paste(original_image, (0, 0), mask_image)

    # 保存masked图像
    image_file = image_file.replace('.jpg','.png')
    mask_image.save(f'./train_mask/{image_file}')
    #break
print("批量处理完成")



posted @ 2024-04-24 19:22  梁君牧  阅读(39)  评论(0编辑  收藏  举报