Draw the boundingbox on image with .jasn file

JeffTeng
·
·
IPFS
·

將圖片標上bunding box的code,下方# Create a Rectangle patch 開始

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np
import json
import os


def draw_dunding_box(jpg_dir,json_dir,set_name,results_dir='/root/notebooks/0858611-2/final_project/caltech_pedestrian_extractor/js_on_image/image_bdbox/'):
    results_dir = results_dir
    fresults_dir = results_dir + set_name
    with open(json_dir) as json_file:
        data = json.load(json_file)

    im = np.array(Image.open(jpg_dir), dtype=np.uint8)

    # Create figure and axes
    fig,ax = plt.subplots(1)

    # Display the image
    ax.imshow(im)

    # Create a Rectangle patch
    for i in range (len(data)):
        bd_box_x,bd_box_y,bd_box_length,bd_box_height = data[i]['pos'][0],data[i]['pos'][1],data[i]['pos'][2],data[i]['pos'][3]
        rect = patches.Rectangle((bd_box_x,bd_box_y),bd_box_length,bd_box_height,linewidth=1,edgecolor='r',facecolor='none')
        # Add the patch to the Axes
        ax.add_patch(rect)
    plt.axis('off')
    plt.plot()
    extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    plt.savefig(fresults_dir +'/'+jpg_dir[-10:-4]+'.png', bbox_inches=extent, pad_inches=0)
    plt.cla()
    plt.clf()
    plt.close()


簡單範例:

加入所有路徑,由於result可能會放到不同資料夾,所以新增set_name,最後結果會存在results_dir+'/'+set_name

json_dir = '/root/notebooks/0858611-2/final_project/caltech_pedestrian_extractor/js_on_image/I00004.json'
jpg_dir = '/root/notebooks/0858611-2/final_project/caltech_pedestrian_extractor/js_on_image/I00004.jpg'
results_dir = '/root/notebooks/0858611-2/final_project/caltech_pedestrian_extractor/js_on_image/'
set_name  = 'label'
draw_dunding_box(jpg_dir,json_dir,set_name,results_dir)

--->



我的作法(需要整理資料混亂的jpg及json):

load檔案裡的圖片和json(可以同資料夾內且不需要依序),檔案不能缺失因為下方直接使用sort

import os
#your data have many set
set_name = 'set00'

#it will load any file path in following floder
script_dir = os.path.dirname('<your/file/dir/with/many/json&jpg>'+set_name+'/*')
jpg_dir  = []
json_dir = []
#add jpg,json in jpg_dir,json_dir list
for dirname, _, filenames in os.walk(script_dir):
    for filename in filenames:
        #[num:num] base on your file name
        if filename[7:10]== 'jpg':
            jpg_dir.append(os.path.join(dirname, filename))
        elif filename[7:11]== 'json':
            json_dir.append(os.path.join(dirname, filename))
            
#sort your file nmae it will sort include group or the other folder 
#for example : set00/group1  set00/group2
sort_jpg  = sorted(jpg_dir, key=lambda x: x[-30:-3])
sort_json = sorted(json_dir, key=lambda x: x[-30:-3])


執行

set_name = 'set00'
for jpg_dir, json_dir in zip(sort_jpg, sort_json):
    draw_dunding_box(jpg_dir,json_dir,results_dir,set_name)


CC BY-NC-ND 2.0 授权

喜欢我的作品吗?别忘了给予支持与赞赏,让我知道在创作的路上有你陪伴,一起延续这份热忱!