text_plain_output_1.png
import cv2

import os

import pandas as pd

IMAGE_SIZE = 224

train = pd.read_csv('./train.csv')
train.index = train['image'].copy()
train['image'] = train['image'].str[:-3] + 'bmp'
train['bbox'] = pd.read_csv('../input/happywhale-boundingbox-yolov5/train.csv', index_col='image')['bbox']
train['bbox'] = train['bbox'].fillna('[]').map(eval)
train

sample_submission = pd.read_csv('./sample_submission.csv')
sample_submission.index = sample_submission['image'].copy()
sample_submission['inference_image'] = sample_submission['image'].str[:-3] + 'bmp'
sample_submission['bbox'] = pd.read_csv('../input/happywhale-boundingbox-yolov5/test.csv', index_col='image')['bbox']
sample_submission['bbox'] = sample_submission['bbox'].fillna('[]').map(eval)
sample_submission

train.to_csv('./train.csv', index=False)
sample_submission.to_csv('./sample_submission.csv', index=False)

def copy_dir(dirname, base_path='../input/happy-whale-and-dolphin/'):
    bboxes = train['bbox'] if dirname == 'train_images' else sample_submission['bbox']
    print('Copying', dirname)
    path = os.path.join(base_path, dirname)
    images = list(os.listdir(path))
    n = len(images)
    for i, f in enumerate(images):
        print(f'{i}/{n}', end='\r')
        image_path = os.path.join(path, f)
        image = cv2.imread(image_path)
        if len(bboxes[f]):
            bbox = bboxes[f][0]
            xmin, ymin, xmax, ymax = bbox
            image = image[ymin:ymax, xmin:xmax]
        image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE), interpolation=cv2.INTER_CUBIC)
        new_path = os.path.join('./', dirname, f.split('.')[0] + '.bmp')
        cv2.imwrite(new_path, image)
copy_dir('train_images')
copy_dir('test_images')