由于yolo做分割需要txt格式的标签
json->txt:
import os
import cv2
import json
import numpy as np
def txt_write(x,img_x,img_y,txt):
data = x['points']
n = 1
for x in data:
for i in x:
if n % 2 == 0:
txt.write(' ' + str(round(i/img_x,6)))
n += 1
else:
txt.write(' ' + str(round(i/img_y,6)))
n += 1
txt.write('\n')
def json2txt(json_path,save_path):
txt = open(save_path,'w')
with open(json_path, "r") as f:
data = f.read()
data = json.loads(data)
img_x = data['imageHeight']
img_y = data['imageWidth']
shapes = data['shapes']
for x in shapes:
#print(x['label'])
#此处面向不同分类,需要改动下面的标签值,如果是多分类,那么需要增加新的if
#只是单分类的话,可以直接去掉if,把里面的模块拿出来用
if x['label']=='huahao':
txt.write('0')
txt_write(x,img_x,img_y,txt)
elif x['label']=='podong':
txt.write('1')
txt_write(x,img_x,img_y,txt)
elif x['label']=='furong':
txt.write('2')
txt_write(x,img_x,img_y,txt)
elif x['label']=='fengtou':
txt.write('3')
txt_write(x,img_x,img_y,txt)
elif x['label']=='zhanwu':
txt.write('4')
txt_write(x,img_x,img_y,txt)
elif x['label']=='zanting':
txt.write('5')
txt_write(x,img_x,img_y,txt)
elif x['label']=='guashang':
txt.write('6')
txt_write(x,img_x,img_y,txt)
txt.close()
# # 单文件测试
# save_dir = "" #文件路径
# name = 'test'
# save_path = save_dir + name + '.txt' # 也可以是.doc
# json_path = './zw100-two.json'
# json2txt(json_path,save_path)
#文件夹
json_dir = ''
save_dir = ''
files = os.listdir(json_dir)
os.makedirs(save_dir, exist_ok=True)
num = 1
for file in files :
name = file[0:-5]
json_path = json_dir + '/' + name + '.json'
save_path = save_dir + '/' + name + '.txt'
json2txt(json_path,save_path)
print(num,'/',len(files),':',name)
num += 1
如果你的json中有中文
类似这样 会报错
Traceback (most recent call last): File "d:/code_python/琢磨琢磨/json2txt.py", line 75, in <module> json2txt(json_path,save_path) File "d:/code_python/琢磨琢磨/json2txt.py", line 25, in json2txt data = json.loads(data) File "D:\Ana\envs\tomato\lib\json\__init__.py", line 348, in loads return _default_decoder.decode(s) File "D:\Ana\envs\tomato\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "D:\Ana\envs\tomato\lib\json\decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Invalid \escape: line 39 column 26 (char 718)
这时候我们需要将json中的这段内容删掉
import os
import json
def delete_line_json(json_path):
# 读取JSON文件
with open(json_path, 'r', encoding='utf-8') as f:
data = f.readlines()
print(data)
# 删除指定行数据
print(len(data))
for i in range(len(data)):
if "imagePath" in data[i]:
del data[i]
break
# 将数据写入文件
with open(json_path, 'w', encoding='utf-8') as f:
f.write(''.join(data))
# delete_line_json('./zw100-two.json')#单json文件测试
# 遍历指定目录下所有的JSON文件
directory=""#json文件夹
def batch_delete_line_json(directory):
for file in os.listdir(directory):
if file.endswith('.json'):
file_path = os.path.join(directory, file)
delete_line_json(file_path)
batch_delete_line_json(directory)
# 调用批量删除函数
# batch_delete_line_json('/path/to/json/folder', 39) # 将39行数据删除
然后再走上面的脚本转txt文件就ok就可以用来做yolo的分割喽
txt转json:
import json
import os
from PIL import Image
import numpy as np
import base64
img_path ="/home/zhh/code_python/txt-json/img/"#图片地址
txt_path ="txt/"#txt地址
json_path="json1/"#json保存地址
labels = os.listdir(txt_path)
#标签名字
class_names = ["vehicle"]
for label in labels:
#设置头部
tupian = {
"version": "5.1.1",
"flags": {},
"shapes": [],
"imagePath": "",
"imageData": "",
"imageHeight": "",
"imageWidth":""
}
#获取图片大小,并保存
img = np.array(Image.open(img_path+label.strip('.txt') + '.jpg'))
sh,sw = img.shape[0],img.shape[1]
tupian["imageHeight"] = sh
tupian["imageWidth"] = sw
tupian["imagePath"]=os.path.basename(img_path)#获取文件名称
# 获取图片数据并保存为base64编码
with open(img_path + label.strip('.txt') + '.jpg', "rb") as f:
image_data = f.read()
base64_data = base64.b64encode(image_data)
tupian["imageData"] = str(base64_data, encoding='utf-8')
#读取base64编码,
# 读取txt
with open(txt_path + label, 'r') as f:
contents = f.readlines()
shapes = []
for content in contents: # 循环每一行内容
labeldicts = []
shapess = {'label': "", "points": [], "group_id": None, "shape_type": "polygon", "flags": {}} # 后缀
content = content.strip('\n').split()
shapess['label'] = class_names[int(content[0])] # 保存label名称
del content[0] # 删除第一个元素,保留坐标
list__ = [content[i:i + 2] for i in range(0, len(content), 2)] # 修改数组,两个一组[x,y]
for i in list__:
x = float(i[0]) * sw
y = float(i[1]) * sh
labeldicts.append([x, y])
shapess["points"] = labeldicts
shapes.append(shapess)
tupian["shapes"] = shapes
# 将字典转换为json字符串
json_str = json.dumps(tupian, indent=2)
# 将json字符串写入文件
json_filename = label.strip('.txt') + '.json'
json_filepath = os.path.join(json_path, json_filename)
with open(json_filepath, 'w') as json_file:
json_file.write(json_str)