This project demonstrates how to detect and crop the contours of a car in an image using OpenCV and Python. It uses edge detection and contour approximation to locate the region of interest (ROI) in the image and extract it.
Read an image and apply pre-processing for edge detection. Detect contours and filter out irrelevant contours based on area. Identify and highlight rectangular contours (for detecting cars). Crop the identified rectangular region from the image. Display the original and cropped images.
Python 3.x OpenCV (cv2) imutils NumPy You can install the necessary dependencies by running:
pip install opencv-python imutils numpy- Place an image of a car (e.g., car0.jpg) in the same directory as the script or update the script with the correct image path.
- Run the script:
python car_contour_detection.py- The script will display the original image with detected contours highlighted, along with a cropped image of the detected region.
-
Pre-processing: The image is first resized and converted to grayscale. A bilateral filter is applied for noise reduction while preserving edges.
-
Edge Detection: The Canny edge detector is used to find edges in the image.
-
Contour Detection: Contours are detected using the cv2.findContours function and sorted by area. The script looks for the largest rectangular contour (which is assumed to be the car).
-
Cropping: Once the rectangular contour is found, the bounding box is used to crop the region of interest (ROI) from the image.
-
Display: The original and cropped images are displayed using OpenCV.