import cv2 import os import sys import time import json #path = "JPEGImages\\3.jpeg" #image = cv2.imread(path) #cropImg = image[0:200,0:200] #cv2.imwrite("ttt.jpg",cropImg) def main(): output_dir = "img_cut" input_dir = "JPEGImages" img_paths = get_img(input_dir) print('图片获取完成 。。。!') cut_img(img_paths,output_dir) def cut_img(img_paths,output_dir): cindex=1; for img in img_paths: json_path = "Annotations\\" + img.split('/')[1].split('.')[0] + ".json" json_data = read_json(json_path) datalist = json_data["labels"] image = cv2.imread(img) index=1 for data in datalist: name = data["name"] +"_cut" rect_y1 = int(data["y1"]) rect_y2 = int(data["y2"]) rect_x1 = int(data["x1"]) rect_x2 = int(data["x2"]) cropImg = image[rect_y1:rect_y2,rect_x1:rect_x2] cv2.imwrite(name+"\\"+str(cindex)+"_"+str(index)+".jpg",cropImg) index+=1 cindex+=1 print("裁剪第"+str(cindex)+"个图片完成") def read_json(filename): jsontext = "" with open(filename, 'r',encoding='utf-8') as file_object: jsontext = file_object.read() jsontext = json.loads(jsontext,encoding='utf-8') return jsontext def get_img(input_dir): img_paths = [] for (path,dirname,filenames) in os.walk(input_dir): for filename in filenames: img_paths.append(path + '/' + filename) print("img_paths:",img_paths) return img_paths def get_json(input_dir): img_paths = [] for (path,dirname,filenames) in os.walk(input_dir): for filename in filenames: data_json = read_json(path + '/' + filename) img_paths.append(path + '/' + filename) print("json_paths:",img_paths) return img_paths if __name__ == '__main__': main()
文章评论