批量json转txt格式,X1,Y1图片中心坐标宽高 ,图片大小不同并归一化,python代码
时间: 2024-04-12 22:30:33 浏览: 12
以下是将批量JSON文件转换为TXT格式,并将坐标转换为图片中心坐标和宽高的Python代码示例:
```python
import json
import csv
import os
def json_to_txt(json_folder, txt_folder):
if not os.path.exists(txt_folder):
os.makedirs(txt_folder)
json_files = os.listdir(json_folder)
for json_file in json_files:
if not json_file.endswith('.json'):
continue
json_path = os.path.join(json_folder, json_file)
txt_file = json_file.replace('.json', '.txt')
txt_path = os.path.join(txt_folder, txt_file)
with open(json_path, 'r') as f:
data = json.load(f)
with open(txt_path, 'w', newline='') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(['X', 'Y', 'Width', 'Height'])
for obj in data['objects']:
x1 = obj['x1']
y1 = obj['y1']
x2 = obj['x2']
y2 = obj['y2']
# 计算中心坐标
width = x2 - x1
height = y2 - y1
x = (x1 + x2) / 2
y = (y1 + y2) / 2
# 归一化处理
x /= data['width']
y /= data['height']
width /= data['width']
height /= data['height']
writer.writerow([x, y, width, height])
# 使用示例
json_folder = 'input_folder'
txt_folder = 'output_folder'
json_to_txt(json_folder, txt_folder)
```
在上述代码中,我们首先创建一个输出文件夹(如果不存在)。然后,我们列出输入文件夹中的所有JSON文件。对于每个JSON文件,我们按照之前的逻辑进行处理,并将结果写入到对应的TXT文件中。请确保将实际的输入文件夹和输出文件夹路径替换为你自己的文件夹路径。