from argparse import ArgumentParser from pathlib import Path import cv2 as cv parser = ArgumentParser() parser.add_argument("--input", default="input/scene.png", help="Source image") parser.add_argument("--output", default="output/scene-crop.png", help="Cropped output image") parser.add_argument("--x", type=int, default=160, help="Left edge of the crop") parser.add_argument("--y", type=int, default=90, help="Top edge of the crop") parser.add_argument("--width", type=int, default=260, help="Crop width in pixels") parser.add_argument("--height", type=int, default=180, help="Crop height in pixels") args = parser.parse_args() image = cv.imread(args.input) if image is None: raise SystemExit(f"could not read input image: {args.input}") source_height, source_width = image.shape[:2] x1 = args.x y1 = args.y x2 = x1 + args.width y2 = y1 + args.height if x1 < 0 or y1 < 0 or x2 > source_width or y2 > source_height: raise SystemExit( "crop rectangle is outside the source image: " f"source={source_width}x{source_height}, " f"box=({x1},{y1})-({x2},{y2})" ) crop = image[y1:y2, x1:x2] output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) if not cv.imwrite(str(output_path), crop): raise SystemExit(f"could not write output image: {output_path}") print(f"source shape: {source_width}x{source_height}") print(f"crop box: x={x1}, y={y1}, width={args.width}, height={args.height}") print(f"slice: image[{y1}:{y2}, {x1}:{x2}]") print(f"crop shape: {crop.shape[1]}x{crop.shape[0]}") print(f"wrote: {output_path}")