from pathlib import Path import cv2 as cv input_path = Path("input/scene.png") output_path = Path("output/contours.png") image = cv.imread(str(input_path)) if image is None: raise SystemExit(f"Could not read {input_path}") gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) _, mask = cv.threshold(gray, 240, 255, cv.THRESH_BINARY_INV) contours, _ = cv.findContours( mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE, ) min_area = 1000 kept_contours = [ contour for contour in contours if cv.contourArea(contour) >= min_area ] annotated = image.copy() cv.drawContours(annotated, kept_contours, -1, (0, 0, 255), 3) output_path.parent.mkdir(parents=True, exist_ok=True) cv.imwrite(str(output_path), annotated) print(f"raw contours: {len(contours)}") print(f"kept contours: {len(kept_contours)}") print(f"minimum area: {min_area}") for index, contour in enumerate(kept_contours, start=1): x, y, width, height = cv.boundingRect(contour) area = cv.contourArea(contour) print( f"contour {index}: area={area:.1f} " f"bbox=({x},{y},{width},{height})" ) print(f"wrote: {output_path}")