1.目的
针对放在同一个文件夹中的文件,使用json文件进行标记分类
2.代码
import os
import json
file_list = os.listdir('D:\img_pre\图片1') # 需要进行标记的文件夹
file_list.sort() # 对文件内容进行排序
# print(file_list)
json_file = 'D:\\Thyroid_new\\Tags.json' # 需要打开或者是修改的json文件
with open(json_file, "r",encoding='utf-8') as f: # 打开json文件进行加载
dict_json = json.load(f)
new_json = {} # new_json是字典,
j = 0 # 这里是进行标记
for i in file_list:
file_name = i.split(".")[0] # 对文件名称进行截取,不需要.jpg
if j<12: # 这里因人而异,我是需要进行两类标记,所以写的一个if,也可以添加或者是删除
new_json[file_name] = ["Benign"] # 格式是文件名:[Benign] ,这里的Benign换成自己的
else:
new_json[file_name] = ["Malignant"]
j = j + 1
print(j)
json_str = json.dumps(new_json) # 将单引号变为双引号,这里至关重要,否则json格式校验的时候,会一直报错
print(json_str)
with open("D:\\Thyroid_new\\Tags.json", "w") as f: # 打开文件进行写入
f.write(json_str)
3.结果
4.统计一下
with open(json_file, "r") as f:
dict_json = json.load(f)
m = 0
b = 0
for i in dict_json:
if "Malignant" in dict_json[i]:
m += 1
else:
b += 1
print("Malignant的数量",m)
print("Benign的数量",b)