How to crop image using yolo format annotation(label)?
본문 바로가기
카테고리 없음

How to crop image using yolo format annotation(label)?

by Migos 2022. 12. 15.
반응형
import cv2
import glob
from tqdm import tqdm

img_files = glob.glob('/home/admin/darknet/*.png')
save_dir = '/home/admin/Downloads/cropped_img'
for img_file in tqdm(img_files):
    img = cv2.imread(img_file)
    dh, dw, _ = img.shape
    full_path = img_file
    file_name = full_path.split('/')[-1]
    txt_file = open((full_path[:-4] + ".txt"), 'r')

    lines = txt_file.readlines()

    for line in lines:
        
        cls, x_center, y_center, w, h = [float(x.strip()) for x in line.split(' ')]

        if cls == 0:

            x_center, y_center, w, h = float(x_center), float(y_center), float(w), float(h)
            x_center = round(x_center * dw)
            y_center = round(y_center * dh)
            w = round(w * dw)
            h = round(h * dh)
            x = round(x_center - w / 2)
            y = round(y_center - h / 2)

            imgCrop = img[y:y + h, x:x + w]
            cv2.imwrite(f'{save_dir}/{file_name}', imgCrop)
            # cv2.imshow("Crop Image",imgCrop)
            # cv2.waitKey(0)
        else:
            pass
반응형

댓글