파이썬/python

[ python ] 이미지에 바운딩 박스 그려넣기

code094 2023. 1. 13. 10:52

1. 이미지의 절댓값 받아옴 (width, height)

def ImageInfo():
    try:
        for file in path_list:
            img = Image.open(path + file)  
            w,h = img.size 
            image_info_dictionary[file] = w,h
            print(f'width : {w} height : {h}')
    except Exception as ex:
        print(f'ImageInfo error : {ex}')

 

 

2. 이미지 그려넣을 label 좌표 값 읽어옴 

def drawbbox_textfile():
    for list in text_list:
        read_file_data = open(text_path + list , 'r')
        bbox_list = []
        for data in read_file_data:
            bbox_list.append(data)
        text_list_dic[list] =  bbox_list

 

 

3. 이미지에 bbox 그린 후 저장 

def drawbbox_jpgfile():
    for image_key, image_value in image_info_dictionary.items():
        for key, value  in text_list_dic.items():
            img = Image.open(path + image_key +'.jpg').convert('RGB')
            draw = ImageDraw.Draw(img)
            for value_data in value:
                w = float(value_data[3])* image_value[0]
                h = float(value_data[4])* image_value[1]
                x1 = float(value_data[1]) * image_value[0] - (w/2) 
                y1 = float(value_data[2]) * image_value[1] - (h/2) 
                x2 = (float(value_data[3])+float(value_data[1]))*image_value[0]
                y2 = (float(value_data[4])+float(value_data[2]))*image_value[1]

                if value_data[0] == '0':
                    draw.rectangle((x1,y1,x2,y2), outline=(000,255,000), width = 3)

            img.save(path +'bbox_image'+ image_key + '.jpg')

- 보통 text 에 클래스 x y widht height 5개