[Python] YOLOv7 한글 라벨 적용 방법

Saka7·2023년 1월 9일
1
post-thumbnail

우선 방법만 간단하게 정리 후 추후 정리예정입니다.

1. 한글지원 폰트 설치

!wget "https://www.wfonts.com/download/data/2016/06/13/malgun-gothic/malgun.ttf"
!mv malgun.ttf /usr/share/fonts/truetype/
import matplotlib.font_manager as fm 
fm._rebuild() 

2. YoloV7 gitclone

!git clone https://github.com/SkalskiP/yolov7.git
%cd yolov7
!git checkout fix/problems_associated_with_the_latest_versions_of_pytorch_and_numpy
!pip install -r requirements.txt

3. data.yaml에서 names 한글로 변경

4. train.py 수정

    # with open(opt.data) as f:
    with open(opt.data, 'r', encoding='utf-8') as f:
        data_dict = yaml.load(f, Loader=yaml.SafeLoader)  # data dict
    is_coco = opt.data.endswith('coco.yaml')

5. 대망의 plots.py 수정

def plot_one_box(x, img, color=None, label=None, line_thickness=3):
    # Plots one bounding box on image img
    tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness
    color = color or [random.randint(0, 255) for _ in range(3)]
    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
    if label:
        tf = max(tl - 1, 1)  # font thickness
        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
        font_size = t_size[1]
        font = ImageFont.truetype("malgun.ttf", font_size, encoding="utf-8")
        t_size = font.getsize(label)
        c2 = c1[0] + t_size[0], c1[1] - t_size[1]
        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        draw = ImageDraw.Draw(img)
        draw.text((c1[0], c2[1]), label, (0, 0, 0), font=font)
        # cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
        return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
def plot_one_box_PIL(box, img, color=None, label=None, line_thickness=None):
    img = Image.fromarray(img)
    draw = ImageDraw.Draw(img)
    line_thickness = line_thickness or max(int(min(img.size) / 200), 2)
    draw.rectangle(box, width=line_thickness, outline=tuple(color))  # plot
    if label:
        fontsize = max(round(max(img.size) / 40), 12)
        font = ImageFont.truetype("malgun.ttf", fontsize)
        txt_width, txt_height = font.getsize(label)
        draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color))
        draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
    return np.asarray(img)

193행

mosaic = plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)

6. detect.py 수정
129행

im0 = plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)


이렇게까지 하면 한글 라벨 완성!

profile
화이팅

0개의 댓글