Detecting corners in images using OpenCV is a common task with applications in various fields, such as image matching, 3D reconstruction, and motion tracking. OpenCV offers multiple methods for corner detection, but the most widely used are Harris Corner Detection and Shi-Tomasi Corner Detection (also known as Good Features to Track). I will now provide a detailed explanation of these two methods.
1. Harris Corner Detector
The Harris Corner Detection algorithm is a classic approach for corner detection, based on the response of the autocorrelation function of a local window in the image. When the window is moved around a corner point, this response exhibits significant changes.
Implementation Steps:
- Convert the image to grayscale, as corner detection is typically performed on single-channel images.
- Apply the Harris Corner Detection algorithm using the function
cv2.cornerHarris(). - Apply thresholding to the results to identify regions where the response intensity meets the criteria for being a corner.
- Mark these detected corners on the original image.
Code Example:
pythonimport cv2 import numpy as np # Read image img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Harris Corner Detection gray = np.float32(gray) dst = cv2.cornerHarris(gray, blockSize=2, ksize=3, k=0.04) # Result dilation for improved visualization dst = cv2.dilate(dst, None) # Thresholding to mark corners img[dst > 0.01 * dst.max()] = [0, 0, 255] # Display image cv2.imshow('Harris Corners', img) cv2.waitKey(0) cv2.destroyAllWindows()
2. Shi-Tomasi Corner Detector (Good Features to Track)
The Shi-Tomasi method improves upon Harris Corner Detection by modifying the scoring function used to evaluate corners, often yielding superior results.
Implementation Steps:
- Convert the image to grayscale.
- Apply the Shi-Tomasi Corner Detection using the function
cv2.goodFeaturesToTrack(). - Mark the detected corners on the original image.
Code Example:
pythonimport cv2 import numpy as np # Read image img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Shi-Tomasi Corner Detection corners = cv2.goodFeaturesToTrack(gray, maxCorners=100, qualityLevel=0.01, minDistance=10) corners = np.int0(corners) # Mark corners for i in corners: x, y = i.ravel() cv2.circle(img, (x, y), 3, 255, -1) # Display image cv2.imshow('Shi-Tomasi Corners', img) cv2.waitKey(0) cv2.destroyAllWindows()
With both methods, relevant parameters can be adjusted according to application requirements, such as the sensitivity of corner detection and the maximum number of corners. These techniques are extensively used in computer vision and image processing projects.