import glob import json import os import shutil import random import cv2 import numpy as np import base64 import math import io import PIL.Image import os.path as osp import shapely from shapely.geometry import box, Polygon,MultiPolygon from shapely.geometry import Point def crop(src_path="d:/data/data_train_val_test",dst_path="d:/data/data_crop",win_width=640,win_height=640,step=320): if os.path.exists(dst_path): shutil.rmtree(dst_path) os.mkdir(dst_path) for phase in ["train","val"]: img_num=0 if os.path.exists(dst_path+"/"+phase): shutil.rmtree(dst_path+"/"+phase) os.mkdir(dst_path+"/"+phase) f_phase=open(src_path+"/"+phase+".txt","r",encoding="utf-8") for line in f_phase.readlines(): line=line.strip() ext = line.rsplit(".")[-1] len1 = len(line) - len(ext) json_f = line[:len1] + "json" #json文件 basename = os.path.basename(line) bsname = basename.rsplit(".", 1)[0] parent = os.path.dirname(line) if os.path.exists(json_f): f_json=open(json_f,"rb") else: json_f2 = os.path.join(parent, "cor_" + bsname + ".json") if os.path.exists(json_f2): f_json=open(json_f2,"rb") #print("crop json_f: ",json_f2) #f_json=open(json_f,"rb") json_dict = json.load(f_json) # if img_bsname in ["201406300029"]: # continue img_ext=json_dict["imagePath"].rsplit(".",1)[-1] img=cv2.imread(line) big_h=json_dict["imageHeight"] big_w=json_dict["imageWidth"] for i in range(0,big_w,step): right_i = min(i + win_width, big_w) if right_i==i: continue for j in range(0,big_h,step): json_crop = {"version": "5.1.1", "flags": {}, "shapes": [], "imagePath": "", "imageHeight": 0, "imageWidth": 0,"imageData":""} bottom_j=min(j+win_height,big_h) if bottom_j == j: continue #crop_img=np.zeros([bottom_j-j,right_i-i,3]) #crop_img = img[j:bottom_j,i:right_i,:] #按窗口大小裁剪小图,不够的地方用0填充。 crop_img = np.zeros([win_height, win_width, 3],img.dtype) #print("j:bottom_j,i:right_i:", j,bottom_j,i,right_i,big_w,big_h) crop_img[:bottom_j-j,:right_i-i,:] = img[j:bottom_j,i:right_i,:] new_bsname=str(img_num)+"_"+str(i)+"_"+str(j) json_crop["imagePath"]=new_bsname+"."+img_ext json_crop["imageHeight"]=crop_img.shape[0] json_crop["imageWidth"]=crop_img.shape[1] dst_img_path=dst_path+"/"+phase+"/"+new_bsname+"."+img_ext dst_json_path = dst_path+"/"+phase+"/" + new_bsname + ".json" for shape in json_dict["shapes"]: ps=[] # for p in shape["points"]: # if p[0]>=i and p[0]=j and p[1]0: #只保存有目标的小图 cv2.imwrite(dst_img_path, crop_img) def load_img(filename): # pillow读取tif图片出错,所以只能用opencv读取,再转为pillow # image_pil = PIL.Image.open(img_cv = cv2.imread(img_path) img_cv = cv2.imread(filename) image_pil = PIL.Image.fromarray(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)) with io.BytesIO() as f: ext = osp.splitext(filename)[1].lower() if ext in [".jpg", ".jpeg"]: format = "JPEG" else: format = "PNG" image_pil.save(f, format=format) f.seek(0) return f.read() imageData = base64.b64encode(load_img(dst_img_path)).decode("utf-8") json_crop["imageData"] = imageData jsonOrderedFile = json.dumps(json_crop, ensure_ascii=False, indent=2) with open(dst_json_path, 'w') as jsonfile: jsonfile.write(jsonOrderedFile) f_json.close() img_num += 1 f_phase.close()