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文件