import numpy as np from PIL import Image def crop_and_resize(image_path, bbox_path, crop_path, resize_path): img = Image.open(image_path) width, height = img.size with open(bbox_path, 'r') as f: _, x_center, y_center, _, _ = map(float, f.readline().split()) x_center, y_center = int(x_center * width), int(y_center * height) x1, x2 = max(0, x_center - 128), min(width, x_center + 128) y1, y2 = max(0, y_center - 128), min(height, y_center + 128) crop = img.crop((x1, y1, x2, y2)) assert crop.size == (256, 256) crop.save(crop_path) resize = crop.resize(size=(128, 128), resample=Image.BICUBIC) assert resize.size == (128, 128) resize.save(resize_path) def transform_intrinsic(intrinsic_path, bbox_path, crop_path, resize_path): intrinsic = np.loadtxt(intrinsic_path) fx, fy = intrinsic[0, 0], intrinsic[1, 1] cx, cy = intrinsic[0, 2], intrinsic[1, 2] width, height = cx * 2, cy * 2 with open(bbox_path, 'r') as f: _, x_center, y_center, _, _ = map(float, f.readline().split()) x_center, y_center = int(x_center * width), int(y_center * height) x1, y1 = max(0, x_center - 128), max(0, y_center - 128) K = np.array([[fx, 0, cx - x1], [0, fy, cy - y1], [0, 0, 1]]) np.savetxt(crop_path, K, fmt="%.5f", delimiter=" ") K[:2] /= 2 np.savetxt(resize_path, K, fmt="%.5f", delimiter=" ") if __name__ == "__main__": # crop and resize image image_path = '640x480/image/0000_00.png' bbox_path = '640x480/bbox/0000_00.txt' crop_path = '256x256/image/0000_00.png' resize_path = '128x128/image/0000_00.png' crop_and_resize(image_path, bbox_path, crop_path, resize_path) # transform intrinsic matrix intrinsic_path = '640x480/intrinsic.txt' bbox_path = '640x480/bbox/0000_00.txt' crop_path = '256x256/intrinsic/0000_00.txt' resize_path = '128x128/intrinsic/0000_00.txt' transform_intrinsic(intrinsic_path, bbox_path, crop_path, resize_path)