这一段代码封装了一个类,需要传统一个图片和标注后json文件所在的地址,标注的选项是polygon,主要是用于unet深度学习网络
在初始化时需要输入文件(image+jeson)路径,多分类任务的label_list。会在项目目录下生成一个test_images文件夹,和marks_folder的文件夹
marks_image的制作使用halcon完成的,方便后期自己项目使用。欢迎交流
import os
import numpy as np
import halcon as ha
import json
import shutil
from qtconsole.mainwindow import background
class gen_marks_image():
def __init__(self,path,label_list):
self.path = path
self.label_list = label_list
def get_list_in_path(self):
name_files = os.listdir(self.path)
json_files = []
for name in name_files:
if name.endswith('.json'):
json_files.append(os.path.join(self.path, name))
return json_files
def create_folder(self,json_files):
image_folders = "test_images"
marks_folder = "marks_folder"
if not os.path.exists(image_folders):
os.mkdir(marks_folder)
if not os.path.exists(marks_folder):
os.mkdir(marks_folder)
for json_1 in json_files:
json_name=os.path.split(json_1)[-1]
image_path = os.path.join(self.path, json_name.replace('.json','.jpg'))
shutil.copy(image_path, image_folders)
image00=ha.read_image(image_path)
width,height =ha.get_image_size(image00)
image_marks0 = ha.gen_image_const("byte",int(width[0]),int(height[0]))
with open(json_1,"r") as f:
json_data = json.load(f)
print(json_data["shapes"])
for shape in json_data["shapes"]:
label0 =shape["label"]
gray =self.label_list.index(label0)
points = shape["points"]
row_points=[]
col_points=[]
for point in points:
row_points.append(int(point[1]))
col_points.append(int(point[0]))
print(row_points,col_points)
row_points.append(row_points[0])
col_points.append(col_points[0])
region = ha.gen_region_polygon(row_points,col_points)
print(gray)
image_marks0 = ha.paint_region(region,image_marks0,gray,'fill')
ha.write_image(image_marks0,'jpg',0,marks_folder+"/"+json_name.replace('.json','.jpg'))
def forward(self):
json_files = self.get_list_in_path()
print(json_files)
self.create_folder(json_files)
if __name__ == '__main__':
path = r'C:\Users\Administrator\Desktop\test_image'
label_list = ['back', 'car', 'dog', 'cat']
gen_marks_image(path,label_list).forward()