Detecting the correct outline rectangle of a card image using OpenCV involves several steps, including image preprocessing, edge detection, contour finding, and finally determining the bounding box for the largest contour (which should correspond to the card). Here’s a step-by-step guide:
-
Import necessary libraries:
import cv2
import numpy as np
-
Read the image:
image = cv2.imread('card_image.jpg')
-
Convert the image to grayscale:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
-
Apply Gaussian Blur to reduce noise:
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
-
Use edge detection (e.g., Canny):
edges = cv2.Canny(blurred, 50, 150)
-
Find contours:
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
-
Find the largest contour:
largest_contour = max(contours, key=cv2.contourArea)
-
Approximate the contour to a polygon:
epsilon = 0.02 * cv2.arcLength(largest_contour, True)
approx = cv2.approxPolyDP(largest_contour, epsilon, True)
-
Get the bounding box (rotated rectangle) around the largest contour:
rect = cv2.minAreaRect(largest_contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
-
Draw the bounding box on the original image (optional):
cv2.drawContours(image, [box], 0, (0, 255, 0), 2)
cv2.imshow('Detected Card', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Here’s the complete code:
import cv2
import numpy as np
# Step 1: Read the image
image = cv2.imread('card_image.jpg')
# Step 2: Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Step 3: Apply Gaussian Blur
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Step 4: Edge detection using Canny
edges = cv2.Canny(blurred, 50, 150)
# Step 5: Find contours
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Step 6: Find the largest contour
if contours:
largest_contour = max(contours, key=cv2.contourArea)
# Step 7: Approximate the contour
epsilon = 0.02 * cv2.arcLength(largest_contour, True)
approx = cv2.approxPolyDP(largest_contour, epsilon, True)
# Step 8: Get the bounding box (rotated rectangle)
rect = cv2.minAreaRect(largest_contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
# Step 9: Draw the bounding box on the image
cv2.drawContours(image, [box], 0, (0, 255, 0), 2)
# Display the result
cv2.imshow('Detected Card', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
In this code:
- We read and preprocess the image.
- We detect edges which helps in contour detection.
- We find the contours and select the largest one, assuming it corresponds to the card.
- We approximate the contour to a polygon to get a more accurate shape.
- We find the minimum area rectangle (which can be rotated) that bounds the card and draw it on the image.
This should give you the correct outline of a card in the image.