OpenCV Tutorial
Image Processing
Feature Detection and Description
Drawing Functions
Video Processing
Applications and Projects
Drawing a rectangular shape around objects and extracting them is a common task in computer vision. This can be done by identifying the contours (boundaries) of the object and then drawing a bounding rectangle around it.
In this tutorial, we'll explore how to do this using OpenCV:
pip install opencv-python
import cv2 import numpy as np
image = cv2.imread('path_to_image.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
(contours, _) = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours: # Get the bounding rectangle x, y, w, h = cv2.boundingRect(contour) # Draw the rectangle cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) # Extract the object and save (optional) roi = image[y:y+h, x:x+w] cv2.imwrite(f"object_{contour[0][0][0]}.jpg", roi)
cv2.imshow('Detected Objects', image) cv2.waitKey(0) cv2.destroyAllWindows()
The binarization threshold (127
in the tutorial) can be adjusted based on the image's characteristics. For images with varying illumination, adaptive thresholding (cv2.adaptiveThreshold()
) might yield better results.
Depending on the image, you might need to perform morphological operations like dilation or erosion to enhance or reduce noise before finding contours.
The extracted objects (roi
) can be processed further, for example, for OCR or classification tasks.
Drawing a rectangle around objects and extracting them is a fundamental operation in computer vision. OpenCV provides efficient tools to identify, outline, and extract objects in an image. Proper preprocessing, like adaptive thresholding or morphological operations, can improve the accuracy and reliability of object detection.
Drawing Rectangles Around Objects in OpenCV:
import cv2 import numpy as np # Read the image img = cv2.imread('objects.jpg') # Define the coordinates of the rectangle (x, y, width, height) rectangle = (50, 100, 200, 150) # Draw the rectangle on the image img_with_rectangle = cv2.rectangle(img.copy(), (rectangle[0], rectangle[1]), (rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2) # Display the result cv2.imshow('Rectangle around Object', img_with_rectangle) cv2.waitKey(0) cv2.destroyAllWindows()
Object Detection and Extraction using Rectangular Bounding Boxes in OpenCV:
import cv2 import numpy as np # Read the image img = cv2.imread('objects.jpg') # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply object detection technique (e.g., thresholding) _, binary_img = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY) # Find contours contours, _ = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Extract objects using rectangular bounding boxes for contour in contours: x, y, w, h = cv2.boundingRect(contour) img_with_boxes = cv2.rectangle(img.copy(), (x, y), (x + w, y + h), (0, 255, 0), 2) # Display the result cv2.imshow('Object Detection and Extraction', img_with_boxes) cv2.waitKey(0) cv2.destroyAllWindows()
Drawing Rectangles on Detected Objects in OpenCV:
import cv2 import numpy as np # Read the image img = cv2.imread('objects.jpg') # Apply object detection technique (e.g., thresholding) _, binary_img = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY) # Find contours contours, _ = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw rectangles on detected objects for contour in contours: x, y, w, h = cv2.boundingRect(contour) img_with_rectangles = cv2.rectangle(img.copy(), (x, y), (x + w, y + h), (0, 255, 0), 2) # Display the result cv2.imshow('Rectangles on Detected Objects', img_with_rectangles) cv2.waitKey(0) cv2.destroyAllWindows()
Contour-Based Object Extraction with Rectangles in OpenCV:
import cv2 import numpy as np # Read the image img = cv2.imread('objects.jpg') # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply object detection technique (e.g., thresholding) _, binary_img = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY) # Find contours contours, _ = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Extract objects based on contours and draw rectangles for contour in contours: x, y, w, h = cv2.boundingRect(contour) object_roi = img[y:y+h, x:x+w] img_with_rectangles = cv2.rectangle(img.copy(), (x, y), (x + w, y + h), (0, 255, 0), 2) # Display the result cv2.imshow('Contour-Based Object Extraction', img_with_rectangles) cv2.waitKey(0) cv2.destroyAllWindows()
Extracting Regions of Interest with Rectangular Masks in OpenCV:
import cv2 import numpy as np # Read the image img = cv2.imread('objects.jpg') # Define the coordinates of the rectangular mask (x, y, width, height) mask_coords = (50, 100, 200, 150) # Extract the region of interest (ROI) using the mask roi = img[mask_coords[1]:mask_coords[1] + mask_coords[3], mask_coords[0]:mask_coords[0] + mask_coords[2]] # Display the extracted ROI cv2.imshow('Extracted ROI with Rectangular Mask', roi) cv2.waitKey(0) cv2.destroyAllWindows()
OpenCV Rectangle Drawing and Object Extraction Example:
import cv2 import numpy as np # Read the image img = cv2.imread('objects.jpg') # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply object detection technique (e.g., thresholding) _, binary_img = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY) # Find contours contours, _ = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw rectangles and extract objects for contour in contours: x, y, w, h = cv2.boundingRect(contour) img_with_rectangles = cv2.rectangle(img.copy(), (x, y), (x + w, y + h), (0, 255, 0), 2) object_roi = img[y:y+h, x:x+w] # Display the result cv2.imshow('Rectangle Drawing and Object Extraction', img_with_rectangles) cv2.imshow('Extracted Object', object_roi) cv2.waitKey(0) cv2.destroyAllWindows()
Python Script for Drawing Bounding Boxes and Extracting Objects in OpenCV:
import cv2 import numpy as np def draw_rectangles_and_extract_objects(image_path): # Read the image img = cv2.imread(image_path) # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply object detection technique (e.g., thresholding) _, binary_img = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY) # Find contours contours, _ = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw rectangles and extract objects for contour in contours: x, y, w, h = cv2.boundingRect(contour) img_with_rectangles = cv2.rectangle(img.copy(), (x, y), (x + w, y + h), (0, 255, 0), 2) object_roi = img[y:y+h, x:x+w] # Display the result cv2.imshow('Rectangle Drawing and Object Extraction', img_with_rectangles) cv2.imshow('Extracted Object', object_roi) cv2.waitKey(0) cv2.destroyAllWindows() # Example usage draw_rectangles_and_extract_objects('objects.jpg')
Rectangular Shape Detection and Object Extraction in OpenCV:
import cv2 import numpy as np # Read the image img = cv2.imread('objects.jpg') # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply edge detection (e.g., Canny) edges = cv2.Canny(gray, 50, 150) # Find contours contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Filter rectangular contours (assume a rectangle if it has 4 corners) rectangular_contours = [cnt for cnt in contours if len(cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt, True), True)) == 4] # Draw rectangles and extract objects for contour in rectangular_contours: x, y, w, h = cv2.boundingRect(contour) img_with_rectangles = cv2.rectangle(img.copy(), (x, y), (x + w, y + h), (0, 255, 0), 2) object_roi = img[y:y+h, x:x+w] # Display the result cv2.imshow('Rectangular Shape Detection and Object Extraction', img_with_rectangles) cv2.imshow('Extracted Object', object_roi) cv2.waitKey(0) cv2.destroyAllWindows()
Contour Approximation for Rectangular Shapes in OpenCV:
import cv2 import numpy as np # Read the image img = cv2.imread('objects.jpg') # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply edge detection (e.g., Canny) edges = cv2.Canny(gray, 50, 150) # Find contours contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Approximate contours to reduce points (assume rectangles) rectangular_contours = [cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt, True), True) for cnt in contours] # Filter rectangles (assume a rectangle if it has 4 corners) rectangular_contours = [cnt for cnt in rectangular_contours if len(cnt) == 4] # Draw rectangles and extract objects for contour in rectangular_contours: x, y, w, h = cv2.boundingRect(contour) img_with_rectangles = cv2.rectangle(img.copy(), (x, y), (x + w, y + h), (0, 255, 0), 2) object_roi = img[y:y+h, x:x+w] # Display the result cv2.imshow('Contour Approximation for Rectangular Shapes', img_with_rectangles) cv2.imshow('Extracted Object', object_roi) cv2.waitKey(0) cv2.destroyAllWindows()
Real-Time Object Extraction with Rectangle Drawing in OpenCV:
import cv2 # Initialize camera cap = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = cap.read() # Convert to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Apply object detection technique (e.g., thresholding) _, binary_img = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY) # Find contours contours, _ = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw rectangles and extract objects for contour in contours: x, y, w, h = cv2.boundingRect(contour) frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # Display the result cv2.imshow('Real-Time Object Extraction', frame) # Break the loop on 'q' key press if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the camera and close windows cap.release() cv2.destroyAllWindows()
Drawing Rectangles with OpenCV and NumPy:
import cv2 import numpy as np # Create a black image img = np.zeros((400, 600, 3), dtype=np.uint8) # Define the coordinates of the rectangle (x, y, width, height) rectangle = (50, 100, 200, 150) # Draw the rectangle on the image img = cv2.rectangle(img, (rectangle[0], rectangle[1]), (rectangle[0] + rectangle[2], rectangle[1] + rectangle[3]), (0, 255, 0), 2) # Display the result cv2.imshow('Rectangle Drawing with NumPy', img) cv2.waitKey(0) cv2.destroyAllWindows()