How to visualize image & annotation using JSON file in Python

olxtar·2022년 4월 21일
0
post-thumbnail

참고 : https://stackoverflow.com/questions/68044429/how-to-visulize-image-using-json-file-in-python




JSON파일 사용과, PIL 패키지, Annotation 등의 기초를 위해서 쌩 이미지 (춘식이 이미지)에 Annotation box를 추가하는 작업을 해보자.

[?] PIL 이미지 imagedraw에서 폰트 크기 설정?




0. 경로 및 파일 체크

import os
print("Current Path : ", os.getcwd())
print("Current Path File List : ", os.listdir())

>>>

Current Path :  C:\Users\USER\LHK
Current Path File List :  [...'springmeal.jpg',...]  # springmeal.jpg가 현 디렉토리에 있다




1. 기본 세팅

1-1. 이미지 불러오기 및 체크

from PIL import Image, ImageDraw

img = Image.open('springmeal.jpg')
img.show()

PIL.Image.openshow()하니까 아예 새로운 창으로 이미지가 떠버리네...?
그래서 아래처럼 IPython.display.Image로 함




[+] IPython.display.Image

from IPython.display import Image

img = Image(filename='springmeal.jpg')
display(img)




from PIL import Image, ImageDraw

img = Image.open('springmeal.jpg')
img_resized = img.resize( ( int(img.width/2 ), int(img.height/2) ) )

.resize( (width, height) )를 통해서 이미지 사이즈를 (736,920) \rightarrow (368,460)으로 바꿈



1-2. JSON파일 생성

아래와 같이 JSON파일을 직접 생성해보자.

JSON

  • object

    • position
      • ['face', [110,60,260,180] ]
      • ['mouse', [160,110,230,170] ]
  • info

    • image_name : 'springmeal'
    • image_path : 'springmeal.jpg'
# JSON = {}
JSON = { 
        "object" : 
            
            { 
                "position" : [
                    ['face', [110,60,260,180]  ],
                    ['mouse', [160,110,230,170] ]
                    ]
                    
            }
            ,
        
       "info" : 
           
           {
               "image_name" : "springmeal",
                "image_path" : "springmeal.jpg"
            }
            
            
       }
  • Dic은 {"label_1" : "content_1", ... "label_n", "content_n"}로 구성되고
    접근 시 JSON["label_n"]로 접근

  • List는 ["content_1",... ,"content_n"]로 구성되고
    접근 시 JSON[n]으로 접근





2. 그려보기

2-1. JSON으로 이미지 불러오기

img = Image.open( JSON["info"]["image_path"] )
img_resized = img.resize( ( int(img.width/2 ), int(img.height/2) ) )




2-2. JSON으로 box 그려보기


[+] JSON 접근경로 체크

for i in JSON["object"]["position"]:
    print(i)
    
>>>
['face', [110, 60, 260, 180]]
['mouse', [160, 110, 230, 170]]

# 색상 파레트 준비
color = ['red', 'green']      

drawing = ImageDraw.Draw(img)

for i, box in enumerate(JSON["object"]["position"]):
    text = box[0]
    x1 = box[1][0]
    y1 = box[1][1]
    x2 = box[1][2]
    y2 = box[1][3]

    drawing.rectangle( [x1, y1, x2, y2], outline=color[i], width = 2)
    drawing.text( [x1, y1], text)
    
img_resized.show()

[!] 이미지의 좌상단이 0,0임. 0,Height가 아님 즉, \searrow로 갈수록 x,y값 증가
[!] x1, y1, x2, y2로 사각형 박스 그리는 기준이 box의 좌상(x1,y1)부분에서 우하(x2,y2)부분으로 드래그하는 느낌임.

profile
예술과 기술

0개의 댓글