from argparse import ArgumentParser from pathlib import Path import cv2 as cv INTERPOLATION_METHODS = { "area": cv.INTER_AREA, "linear": cv.INTER_LINEAR, "cubic": cv.INTER_CUBIC, "nearest": cv.INTER_NEAREST, } INTERPOLATION_NAMES = { "area": "INTER_AREA", "linear": "INTER_LINEAR", "cubic": "INTER_CUBIC", "nearest": "INTER_NEAREST", } parser = ArgumentParser() parser.add_argument("--input", default="input/scene.png", help="Source image") parser.add_argument("--output", default="output/scene-resized.png", help="Resized output image") parser.add_argument("--width", type=int, default=360, help="Output width in pixels") parser.add_argument("--height", type=int, default=240, help="Output height in pixels") parser.add_argument( "--interpolation", choices=INTERPOLATION_METHODS, default="area", help="Interpolation method: area for shrinking, linear or cubic for enlarging", ) args = parser.parse_args() if args.width <= 0 or args.height <= 0: raise SystemExit("width and height must be positive integers") input_path = Path(args.input) output_path = Path(args.output) image = cv.imread(str(input_path), cv.IMREAD_COLOR) if image is None: raise SystemExit(f"could not read input image: {input_path}") source_height, source_width = image.shape[:2] resized = cv.resize( image, (args.width, args.height), interpolation=INTERPOLATION_METHODS[args.interpolation], ) output_path.parent.mkdir(parents=True, exist_ok=True) if not cv.imwrite(str(output_path), resized): raise SystemExit(f"could not write output image: {output_path}") written = cv.imread(str(output_path), cv.IMREAD_COLOR) if written is None: raise SystemExit(f"could not read resized image: {output_path}") written_height, written_width = written.shape[:2] if (written_width, written_height) != (args.width, args.height): raise SystemExit( "resized image has unexpected dimensions: " f"expected={args.width}x{args.height}, " f"actual={written_width}x{written_height}" ) x_scale = args.width / source_width y_scale = args.height / source_height print(f"read: {input_path}") print(f"source: {source_width}x{source_height}") print(f"target: {args.width}x{args.height}") print(f"scale: {x_scale:.3f}x{y_scale:.3f}") print(f"interpolation: {args.interpolation} ({INTERPOLATION_NAMES[args.interpolation]})") print(f"wrote: {output_path}") print(f"verified: {written_width}x{written_height}")