- imread读入图片;
- cvtColor转为灰度图;
- threshold二值化图片;
- Canny边缘检测;
- HoughCircles霍夫变换检测圆形;得到圆心和半径就可以计算矩形框的左上角和右下角的坐标了。
from glob import glob
import json
import numpy as np
import cv2
import os
img_path = './Data/images'
load_json_path = './Data/json'
save_crop_path = './Data/saveimg'
save_json_path = './Data/savejson'
def crop_jsons(jf,save_data_dir,x,y,imageHeight,imageWidth):
'''
读取json文件
'''
with open(jf, "r") as f:
json_str = f.read()
your_dict = json.loads(json_str)
your_dict["imageData"]= None
your_dict["imagePath"]= os.path.basename(jf)[:-5]+'.jpg'
your_dict["imageHeight"]= imageHeight
your_dict["imageWidth"]= imageWidth
shapes = your_dict["shapes"]
for label in range(len(shapes)):
for k in range(len(shapes[label]["points"])):
shapes[label]["points"][k][0]=shapes[label]["points"][k][0]-x
shapes[label]["points"][k][1]=shapes[label]["points"][k][1]-y
'''
保存json文件
'''
if not os.path.exists(save_data_dir):
os.mkdir(save_data_dir)
save_dir=os.path.join(save_data_dir, os.path.basename(jf))
with open(save_dir, "w", encoding="UTF-8") as f1:
json.dump(your_dict,f1, ensure_ascii=False,indent = 2)
def draw_min_rect_rectangle(mask_path):
if not os.path.exists(save_crop_path):
os.mkdir(save_crop_path)
file_names = os.listdir(mask_path)
for name in file_names:
if name.endswith('.jpg'):
print(name)
img = cv2.imread(os.path.join(mask_path,name))
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_,img_thres = cv2.threshold(img_gray, 10, 255, cv2.THRESH_BINARY)
thresh = cv2.Canny(img_thres,100,200)
circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 2, minDist=3000, param1=10, param2=30, minRadius=300)
img_RGB = np.copy(img)
circle = circles[0][0]
cx, cy, r = circle[0], circle[1], circle[2]
h,w = img_RGB.shape[0], img_RGB.shape[1]
x1,y1,x2,y2 = int(max(cx-r,0)), int(max(cy-r,0)), int(min(cx+r,w)), int(min(cy+r,h))
img_RGB = img_RGB[y1:y2,x1:x2]
cv2.imwrite(save_crop_path+'/'+name, img_RGB)
json_file = load_json_path + '/' + name.split('.jpg')[0] + '.json'
crop_jsons(json_file,save_json_path,x1,y1,(y2-y1),(x2-x1))
if __name__ == '__main__':
draw_min_rect_rectangle(img_path)