0628 개발일지

이나겸·2022년 6월 28일
0

1. 학습내용

data call 코드

import gdown
import argparse

"""pip install gdown"""
"""사용법 : python3 data_call.py --data FaceMaskDetection"""

file_destinations = {
    'FaceMaskDetection': 'Face Mask Detection.zip', }
file_id_dic = {
    'FaceMaskDetection': '1pJtohTc9NGNRzHj5IsySR39JIRPfkgD3'
}


def download_file_from_google_drive(id_, destination):
    url = f"https://drive.google.com/uc?id={id_}"
    output = destination
    gdown.download(url, output, quiet=True)
    print(f"{output} download complete")


parser = argparse.ArgumentParser(
    description='data loader ... '
)
parser.add_argument('--data', type=str, help='key for selecting data..!!')

args = parser.parse_args()


download_file_from_google_drive(
    id_=file_id_dic[args.data], destination=file_destinations[args.data]
)


# download_file_from_google_drive(
#     id=file_id_dic["FaceMaskDetection"],
#     destination=file_destinations["FaceMaskDetection"]
# )

# 압축 풀기
test_file_name = "./Face Mask Detection.zip"

with ZipFile(test_file_name, 'r') as zip:
    zip.printdir()
    zip.extractall()

data exploration

import os
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mping
import matplotlib.patches as patches
from bs4 import BeautifulSoup
import natsort  # 파일명이 숫자일 때 정렬

# 주어진 이미지에 바운딩 박스를 시각화 해서 올바르게 레이블링 되어있는지 확인하는 작업
img_list = natsort.natsorted(glob.glob("./Face Mask Detection/images/*.png"))
label_list = natsort.natsorted(glob.glob("./Face Mask Detection/annotations/*.xml"))

# image와 label 갯수 확인
# print(len(img_list), len(label_list))

# 10개까지 잘 출력되는 지 확인
# print(img_list[:10])
# print()
# print(label_list[:10])

""" 바운딩 박스 시각화를 위한 함수 정의 """
def generate_box(obj):
    xmin = float(obj.find("xmin").text)
    ymin = float(obj.find("ymin").text)
    xmax = float(obj.find("xmax").text)
    ymax = float(obj.find("ymax").text)

    return [xmin, ymin, xmax, ymax]

def generate_label(obj):
    if obj.find("name").text == 'with_mask':
        return 1
    elif obj.find("name").text == 'mask_weared_incorrect':
        return 2
    return 0

def generate_target(file):
    with open(file) as f :
        data = f.read()
        soup = BeautifulSoup(data, "html.parser")
        objects = soup.find_all("object")

        boxes = []
        labels = []
        for i in objects:
            boxes.append(generate_box(i))
            labels.append(generate_label(i))

        target = {}
        target["boxes"] = boxes
        target["labels"] = labels

        return target

# box 정보 가져오기
print(img_list.index('./Face Mask Detection/images\\maksssksksss15.png'))
bbox = generate_target(label_list[15])
print(bbox)

def plot_image(img_path, annotation):
    img = img_path.permute(1, 2, 0)

    fig, ax = plt.subplots(1)
    ax.imshow(img)

    for idx in range(len(annotation['boxes'])):
        xmin, ymin, xmax, ymax = annotation["boxes"][idx]

        if annotation['labels'][idx] == 0:
            rect = patches.Rectangle(
                (xmin, ymin), (xmax - xmin), (ymax - ymin), linewidth=1, edgecolor='r', facecolor='none'
            )
        elif annotation['labels'][idx] == 1:
            rect = patches.Rectangle(
                (xmin, ymin), (xmax - xmin), (ymax - ymin), linewidth=1, edgecolor='g', facecolor='none'
            )
        else:
            rect = patches.Rectangle(
                (xmin, ymin), (xmax - xmin), (ymax - ymin), linewidth=1, edgecolor='b', facecolor='none'
            )
        ax.add_patch(rect)

    plt.show()
bbox = generate_target(label_list[520])
plot_image(img_list[520], bbox)

2. 학습소감

albumentation을 오랜만에 썼더니 헷갈린다..
다시 찾아보고 aug_test 코드를 완성시켜야겠다.

0개의 댓글