批量将图片分别旋转90、180、270度,并将对应的点标注的json文件也进行相应调整,做到数据增强的效果

from PIL import Image
import os
import json

def rotate_images_and_jsons(input_folder):
    output_folder = os.path.join(input_folder, "rotated_images")
    os.makedirs(output_folder, exist_ok=True)

    for filename in os.listdir(input_folder):
        if filename.endswith(".jpg"):
            image_path = os.path.join(input_folder, filename)
            json_path = os.path.join(input_folder, filename.replace(".jpg", ".json"))

            # Load JSON data
            with open(json_path, 'r', encoding='utf-8') as json_file:
                json_data = json.load(json_file)

            image = Image.open(image_path)

            # Rotate the image by 90, 180, and 270 degrees
            for angle in [90, 180, 270]:
                rotated_image = image.rotate(angle, expand=True)

                # Save rotated images with a default quality value
                rotated_image_path = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}_{angle}deg.jpg")
                rotated_image.save(rotated_image_path, quality=160)

                # Update JSON data for rotated image
                rotated_json_data = update_json_for_rotation(json_data, image.size, angle, os.path.basename(rotated_image_path))
                rotated_json_path = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}_{angle}deg.json")
                with open(rotated_json_path, 'w', encoding='utf-8') as rotated_json_file:
                    json.dump(rotated_json_data, rotated_json_file, indent=4, ensure_ascii=False)

def update_json_for_rotation(json_data, image_size, angle, image_path):
    width, height = image_size
    if angle == 90:
        rotated_json_data = [{'points': [[point[1], width - point[0]]], 'label': shape['label'], 'group_id': shape['group_id'], 'shape_type': shape['shape_type'], 'flags': shape['flags']} for shape in json_data['shapes'] for point in shape['points']]
    elif angle == 180:
        rotated_json_data = [{'points': [[width - point[0], height - point[1]]], 'label': shape['label'], 'group_id': shape['group_id'], 'shape_type': shape['shape_type'], 'flags': shape['flags']} for shape in json_data['shapes'] for point in shape['points']]
    elif angle == 270:
        rotated_json_data = [{'points': [[height - point[1], point[0]]], 'label': shape['label'], 'group_id': shape['group_id'], 'shape_type': shape['shape_type'], 'flags': shape['flags']} for shape in json_data['shapes'] for point in shape['points']]
    else:
        rotated_json_data = json_data['shapes']  # No rotation
    return {'version': json_data['version'], 'flags': json_data['flags'], 'shapes': rotated_json_data, 'imagePath': image_path, 'imageData': json_data['imageData'], 'imageHeight': json_data['imageHeight'], 'imageWidth': json_data['imageWidth']}

# Replace 'input_folder' with your folder containing images and JSON files
rotate_images_and_jsons('./predata')

只需修改一个路径rotate_images_and_jsons,此路径下存放图片和对应json文件

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个可以实现批量复制标注JSON 文件到未标注图片上,并对应命名新的 JSON 文件Python 代码示例: ```python import os import json import shutil def batch_copy_and_rename_json(source_dir, image_dir, destination_dir): if not os.path.exists(destination_dir): os.makedirs(destination_dir) for file_name in os.listdir(source_dir): if file_name.endswith('.json'): json_file = os.path.join(source_dir, file_name) image_name = file_name[:-5] # 去掉文件扩展名 ".json" image_file = os.path.join(image_dir, image_name) if os.path.exists(image_file): destination_file = os.path.join(destination_dir, f"{image_name}.json") # 复制图片 shutil.copy(image_file, destination_dir) # 更新 JSON 文件中的图片路径 with open(json_file, 'r') as f: data = json.load(f) data['image_path'] = os.path.join(destination_dir, f"{image_name}.jpg") with open(destination_file, 'w') as f: json.dump(data, f, indent=4) print(f"已复制并重命名 {file_name} 到 {destination_file}") else: print(f"未找到与 {file_name} 相对应图片文件") print('批量复制和重命名完成!') # 设置源目录、图片目录和目标目录 source_directory = '/path/to/source/directory' # 替换为实际源目录的路径 image_directory = '/path/to/image/directory' # 替换为实际图片目录的路径 destination_directory = '/path/to/destination/directory' # 替换为实际目标目录的路径 # 执行批量复制和重命名 batch_copy_and_rename_json(source_directory, image_directory, destination_directory) ``` 请确保替换代码中的 `source_directory`、`image_directory` 和 `destination_directory` 变量为实际的源目录、图片目录和目标目录的路径。此代码将遍历源目录中的所有 JSON 文件,根据文件名称找到对应图片文件,并将其复制到目标目录中。同时,代码还会更新 JSON 文件中的图片路径,并将其保存到目标目录中,文件名与对应图片文件名一致。在复制和重命名完成后,将输出相应的提示消息。 提醒:在运行代码之前,请确保已安装 `shutil` 和 `json` 模块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值