python opencv找到图中的圆的最小外接矩形,并将坐标保存到json

  • imread读入图片;
  • cvtColor转为灰度图;
  • threshold二值化图片;
  • Canny边缘检测;
  • HoughCircles霍夫变换检测圆形;得到圆心和半径就可以计算矩形框的左上角和右下角的坐标了。
#  -*- coding: utf-8 -*- 
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):
    # for jf in glob(load_data_dir+'*.json'):
    '''
    读取json文件
    '''
    with open(jf, "r") as f:
        json_str = f.read()
    your_dict = json.loads(json_str) #json格式转python格式
    your_dict["imageData"]= None #python中None即是null
    your_dict["imagePath"]= os.path.basename(jf)[:-5]+'.jpg' #获取文件名
    your_dict["imageHeight"]= imageHeight
    your_dict["imageWidth"]= imageWidth
    
    shapes = your_dict["shapes"]  #label保存在shapes属性里面      
    for label in range(len(shapes)): #label的总数
        for k in range(len(shapes[label]["points"])): #label中标签点的总数
            shapes[label]["points"][k][0]=shapes[label]["points"][k][0]-x #x是裁剪点的x坐标
            shapes[label]["points"][k][1]=shapes[label]["points"][k][1]-y #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)
            # 1. imread读入图片
            img = cv2.imread(os.path.join(mask_path,name))
            
			# 2. cvtColor转为灰度图
            img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            
			# 3. threshold二值化图片
            _,img_thres = cv2.threshold(img_gray, 10, 255, cv2.THRESH_BINARY)
            # cv2.imshow('thres',img_thres)
            # cv2.imwrite(save_crop_path+'/'+name, img_thres)

			# 4. Canny边缘检测
            thresh = cv2.Canny(img_thres,100,200)
            # cv2.imwrite(save_crop_path+'/'+name, thresh)
			
			# 5. HoughCircles霍夫变换检测圆形
            circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 2, minDist=3000, param1=10, param2=30, minRadius=300)
            # print(circles)
            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))
            # cv2.rectangle(img_RGB,(int(max(cx-r,0)),int(max(cy-r,0))), (int(min(cx+r,w)),int(min(cy+r,h))), (132, 135, 239), 2)
            img_RGB = img_RGB[y1:y2,x1:x2]
            cv2.imwrite(save_crop_path+'/'+name, img_RGB)
            # json_file = load_json_path + '/' + name.strip('.jpg') + '.json'
            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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值