Coding-python-标签-deepfasion数据集json2txt

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import json
from PIL import Image, ImageDraw
import glob

def create_yolo_txt(json_data, image_width, image_height, txt_file_path):
"""Convert JSON data to YOLO format and save to TXT file."""
with open(txt_file_path, 'w') as f:
for item_key in ['item1', 'item2']:
if item_key in json_data:
bbox = json_data[item_key]['bounding_box']
cat_id = json_data[item_key]['category_id']

# Convert bounding box coordinates to YOLO format
x_center = (bbox[0] + bbox[2]) / (2 * image_width)
y_center = (bbox[1] + bbox[3]) / (2 * image_height)
width = (bbox[2] - bbox[0]) / image_width
height = (bbox[3] - bbox[1]) / image_height

line = f"{cat_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n"
f.write(line)

def draw_bounding_boxes(json_data, image, output_image_path):
"""Draw bounding boxes on the image and save."""
draw = ImageDraw.Draw(image)
for item_key in ['item1', 'item2']:
if item_key in json_data:
bbox = json_data[item_key]['bounding_box']
draw.rectangle(bbox, outline='red')
image.save(output_image_path)

def process_images_and_jsons(image_folder, json_folder, txt_output_folder, result_image_folder):
"""Process all images and JSON files."""
if not os.path.exists(txt_output_folder):
os.makedirs(txt_output_folder)
if not os.path.exists(result_image_folder):
os.makedirs(result_image_folder)

for json_file in glob.glob(os.path.join(json_folder, '*.json')):
base_name = os.path.splitext(os.path.basename(json_file))[0]
image_file = os.path.join(image_folder, f'{base_name}.jpg')

if os.path.isfile(image_file):
with open(json_file, 'r') as f:
data = json.load(f)

image = Image.open(image_file)
image_width, image_height = image.size

txt_file_path = os.path.join(txt_output_folder, f'{base_name}.txt')
create_yolo_txt(data, image_width, image_height, txt_file_path)

output_image_path = os.path.join(result_image_folder, f'{base_name}_result.jpg')
draw_bounding_boxes(data, image, output_image_path)

# Set your folders here
image_folder = 'train\\train\\image'
json_folder = 'train\\train\\annos'
txt_output_folder = 'train\\train\\lables' #结果
result_image_folder = 'train\\train\\result' #框框后的结果

process_images_and_jsons(image_folder, json_folder, txt_output_folder, result_image_folder)