问题需求:
拥有两个文件夹,一个保存图片image,一个保存标签文件,要求把标签文件中的标注提取出来,并在图片中画出来
os.walk()
迭代读取文件夹以及相应的文件列表os.listdir
直接读取文件夹下的文件列表# 通过os.walk()读取文件夹以及相应的文件列表 def get_file_list(path): file_list=[] for dir_list,folder,file in os.walk(path): file_list=file return file_list #通过os.listdir()读取文件夹下的文件列表 def get_file_list2(path): file_list=os.listdir(path) return file_list file_list=get_file_list2(r"E:\temp\AI\label") print(file_list)
查看json文件结构,对应找到坐标所在的位置:
cv2.rectangle(img, pt1, pt2, color, thickness=None )
{ "version": "3.16.5", "flags": {}, "shapes": [ { "label": "0", "line_color": null, "fill_color": null, "points": [ [ 2720.0, 1094.0 ], [ 2768.0, 1158.0 ] ], "shape_type": "rectangle", "flags": {} } ], ... }
那么代码就如下所示:
import json import cv2 path_label=r"E:\temp\AI\label" path_img=r"E:\temp\AI\image" path_result=r"E:\temp\AI\result" # 通过遍历将图像纷纷画框 for file in file_list: txt=open(os.path.join(path_label,file)) load_json=json.load(txt) for shape in load_json["shapes"]: left_top=(int(shape["points"][0][0]),int(shape["points"][0][1])) right_bottom=(int(shape["points"][1][0]),int(shape["points"][1][1])) #对象进行画框 img_name=file.split(".")[0]+".jpeg" img=cv2.imread(os.path.join(os.path.join(path_img,img_name))) cv2.rectangle(img, left_top,right_bottom, (0, 255, 0), 2) cv2.imwrite(os.path.join(path_result,img_name), img)
比如其中一个图像的一个缺陷位置就被标注出来