解析json文件-Python代码分享

import cv2
import numpy as np
import os
import numpy as np
#

from numpy import array
import json
import os
from PIL import Image
def img_paste(img_path, polygon_dict, save_name=False):
    """

    :param img_path:
    :param polygon_dict:
    :param save_name:
    :return:
    """

if __name__ == '__main__':

    ### #先读json


    data_path = r'F:/sef/arrow/OutputJson'
    output_path = r'F:/dataset/extracted_imgs'
    info_all = {}

#解析json
    arrow_dict_json  = {
        'imgs':"0",
        'path':'1',
        'objects':'2',
        'confidence':'3',
        'points':'4',
        'category':5,

    }
    count = 1
    count_img_noexist = 0
    count_img_exist = 0
    # 将 Python 字典类型转换为 JSON 对象
    # 解析json
    json_str = json.dumps(arrow_dict_json)
    print(json_str)
    print(type(json_str))

    # 将 Python 字典直接输出到文件
    with open('pengjunlee.json', 'w', encoding='utf-8') as f:
        json.dump(json_str, f, ensure_ascii=False, indent=4)

    #递归遍历所有的json文件
    # for i in arrow_dict_json:
    for root, dirs, files in os.walk(data_path, topdown=False):
        for name in files:
            if name.endswith('json'):
                print(os.path.join(root, name))


  #提取信息

    arrow_dict = {
        0:0,
        1:'a_wf',
        2: 'a_wfl',
        3: 'a_wl',
        4:'a_wr',
        5:'a+wfr',
        6:'a_W_lc',
        7:'a_w_ls',

    }
    count = 1
    count_img_noexist = 0
    count_img_exist = 0

#
# #用opencv画框
bgr_img_path = cv2.imread(r"F:/sef/arrow/Images/+.jpg",0)
# gray_img = cv2.cvtColor(bgr_img_path,cv2.COLOR_BGR2GRAY,cv2.IMREAD_COLOR)  #灰度图
# th , binary = cv2.threshold(0,255,cv2.THRESH_OTSU,)  #将otsu法返回的阈值作为二值化的参数。
# contours ,hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)   #cv2.findContours()函数接受的参数为二值图  所以读取的图像要先转成灰度的,再转成二值图,
# cv2.drawContours(bgr_img_path,contours,-1,(0,0,255),3)
# bounding_boxes = [cv2.boundingRect(contours) for contours in contours]


#findContour用于找到不规则形状的轮廓
image, contours, hier = cv2.findContours(thresh,
                                         cv2.RETR_EXTERNAL,
                                         cv2.CHAIN_APPROX_SIMPLE)


for contour in contours:
    #计算一个简单的边界框
    x,y,w,h = cv2.boundingRect(contour)
    #画出边界框
    cv2.rectangle(img, (x,y), (x+w, y+h),(0,0,255),2)
    #计算包围目标的最小矩形区域
    rect = cv2.minAreaRect(contour)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(img, [box], 0, (255,0,255), 2)
    #cv2.minEnclosingCircle函数返回一个二元组,第一个元组为圆心坐标,第二个为半径
    (x0,y0), radius = cv2.minEnclosingCircle(contour)
    center = (int(x0), int(y0))
    radius = int(radius)
    img = cv2.circle(img, center, radius, (0,255,255))


    # 坐标提取

def coordinate_extract(img_path, coordinate_list):
    """

    """
    coord_x = []
    coord_y = []
    for i in range(len(coordinate_list)):
        if i % 2 == 0:
            coord_x.append(coordinate_list[i])
        else:
            coord_y.append(coordinate_list[i])

    # xmin ymin xmax ymax
    return min(coord_x), min(coord_y), max(coord_x), max(coord_y)

#框选

def bbox(bounding_boxes,contours,):
    object_dict = {}

    for bbox in bounding_boxes:
        [x,y,w,h] = bbox
        #用绿色(0,255,0)来画出最小的矩形框
        # array=array.astype( np.uint8 )

    x,y,w,h = cv2.boundingRect(bgr_img_path)
    for bbox in bounding_boxes:
        [x, y, w, h] = bbox
        cv2.rectangle(bgr_img_path, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # cv2.rectangle(bgr_img,(x,y),(x+w,y+h),(153,153,0),5)
    # cv2.rectangle(bgr_img,(x,y),(x+w,y+h),(0,255,0),2)
    cv2.rectangle(bgr_img_path, (x, y), (x + w, y + h), (153, 153, 0), 5)
    new_image = bgr_img_path[y-2:y+h+2, x-2:x + w + 2] #先用y确定高,再用x确定宽,画出矩形
    bounding_boxes = [cv2.boundingRect(cnt) for cnt in contours]   #cnt是cv2.findContours()函数返回的轮廓

    with open(arrow_dict, 'r') as f:
        org_data = [i.strip().split(';') for i in f.readlines()]
        # print(org_data)
        arrow_dict['path'] = data_path
        objects_list = []

    for idx, org_target in enumerate(org_data):
        object_dict = {}
        coordinates = coordinate_extract(img_path, org_target[1:-2])
        object_dict['coordinate'] = {
            'xmin': coordinates[0],
            'ymin': coordinates[1],
            'xmax': coordinates[2],
            'ymax': coordinates[3]
        }
        # 对图片进行保存
        imgs_dir = os.path.join(output_path, str(object_dict['category']))
        if not os.path.exists(imgs_dir):
            os.mkdir(imgs_dir)


            print(img_path)

            org_img = Image.open(img_path)
            extracted_img = org_img.crop(
                (int(coordinates[0]), int(coordinates[1]), int(coordinates[2]), int(coordinates[3])))
            extracted_img.save(
                os.path.join(imgs_dir,
                             '%s_%d_%s.jpg' % (name.split('.')[0], idx + 1, object_dict['cls'])))
            # 将目标存储为json文件
            with open('annotations.json', 'w') as f:
                json.dump(info_all, f)

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值