json文件提取圖片(使用多個座標畫閉合區域)

主要參考:https://www.geeksforgeeks.org/python-pil-imagedraw-draw-polygon-method/
主要是通過img1 = ImageDraw.Draw(img)使用ImageDraw.Draw來畫圖;需要注意的點就是保存的時候圖片應該爲png或bmp格式,如果是jpg格式,像素值會和自己定義的不太一樣,像素值具體參照rgb顏色表(https://tool.oschina.net/commons?type=3);

from __future__ import division, print_function, absolute_import
import skimage
import cv2
import numpy as np
import os
import json
from PIL import Image,ImageDraw
color_code={}
color_code['yellow']='#FFFF00'
color_code['red']='#FF0000'
color_code['blue']='#0000FF'
color_code['green']='#00FF00'
color_code['magenta']='#FF00FF'
color_code['cyan']='#00FFFF'
dir='.../json_files/'
for file in os.listdir(dir):
    json_file = dir + file
    data = json.load(open(json_file))
    img = Image.new('RGB', [640, 512], color_code['cyan'])
    img1 = ImageDraw.Draw(img)
    label_idx_list = list(np.arange(len(data['shapes'])))
    for i in label_idx_list:
        if data['shapes'][i]['label'] == 'lvw':
            xy = []
            for xy_tuple in data['shapes'][i]['points']:
                xy += xy_tuple
            img1.polygon(xy, fill=color_code['red'], outline=color_code['red'])
            label_idx_list.remove(i)
    for j in label_idx_list:
        if data['shapes'][j]['label'] == 'lv':
            xy = []
            for xy_tuple in data['shapes'][j]['points']:
                xy += xy_tuple
            img1.polygon(xy, fill=color_code['yellow'], outline=color_code['yellow'])
        if data['shapes'][j]['label'] == 'la':
            xy = []
            for xy_tuple in data['shapes'][j]['points']:
                xy += xy_tuple
            img1.polygon(xy, fill=color_code['blue'], outline=color_code['blue'])
        if data['shapes'][j]['label'] == 'rv':
            xy = []
            for xy_tuple in data['shapes'][j]['points']:
                xy += xy_tuple
            img1.polygon(xy, fill=color_code['green'], outline=color_code['green'])
        if data['shapes'][j]['label'] == 'ra':
            xy = []
            for xy_tuple in data['shapes'][j]['points']:
                xy += xy_tuple
            img1.polygon(xy, fill=color_code['magenta'], outline=color_code['magenta'])
    img.save('.../json_label/'+ os.path.splitext(file)[0] + '.png')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章