Corner and Keypoint Detection
Corners and keypoints are distinct image regions that can be tracked across frames or matched between different views, acting as stable anchors for computer vision tasks.
Why Does This Exist?
When comparing two images—whether to stitch a panorama, track an object in a video, or construct a 3D model from multiple views—an algorithm needs reliable reference points. You cannot simply compare every pixel in image A to every pixel in image B; that is computationally impossible and highly sensitive to slight shifts in lighting or rotation.
Instead, we need to extract sparse, distinct features from an image that remain identifiable even if the image is scaled, rotated, or partially obscured. These features are called keypoints. Corners are excellent keypoints because, unlike a flat region or a straight edge, a corner represents a point where image intensity changes sharply in multiple directions. This makes it a highly localizable anchor. The development of robust corner and keypoint detectors like the Harris Corner Detector and SIFT (Scale-Invariant Feature Transform) fundamentally enabled classical object tracking, image stitching, and 3D reconstruction long before deep learning took over.
Think of It Like This
Imagine you are given two different jigsaw puzzle pieces that belong to the same section of the sky. If the pieces only show flat blue sky, they are impossible to match—there are no unique features. If one piece has a straight white contrail, you know they might align along that line, but you can still slide them back and forth along the contrail.
However, if both pieces contain the exact corner of a cloud where it sharply cuts against the blue sky, you can align them instantly and precisely in both the horizontal and vertical directions. A flat region has no shifts, an edge has a shift in only one direction, but a corner has shifts in all directions, making it a perfect, unambiguous anchor.
How It Actually Works
Finding corners involves mathematical techniques that search for regions of high contrast in multiple directions. The classical approach, pioneered by the Harris Corner Detector, works through a sliding window mechanism.
1. The Sliding Window
The algorithm conceptually slides a small window over the image and calculates the difference in pixel intensities between the window's current position and slightly shifted positions in all directions.
- Flat region: Shifting the window in any direction results in almost zero change in intensity.
- Edge: Shifting the window along the edge results in no change, but shifting perpendicular to the edge results in a large change.
- Corner: Shifting the window in any direction results in a large change in intensity.
2. The Structure Tensor
Instead of actually shifting the window in every possible direction, the Harris detector uses the image gradients (derivatives). It computes the horizontal derivative () and vertical derivative () for every pixel. It then constructs a matrix, known as the Structure Tensor or the second-moment matrix, over the local window:
Here, is a weighting function, typically a Gaussian, that gives more importance to pixels near the center of the window.
3. Eigenvalues and the Corner Response
The behavior of the local window is entirely captured by the two eigenvalues, and , of the matrix .
- If both and are small, the region is flat.
- If one eigenvalue is large and the other is small, the region is an edge.
- If both and are large, the region is a corner.
To avoid the computationally expensive eigenvalue calculation, the Harris detector computes a response score using the determinant and trace of the matrix:
Where and . If is greater than a certain threshold, the pixel is marked as a corner.
4. Scale Invariance (SIFT and SURF)
While the Harris detector is rotation-invariant (a corner is a corner even if you spin the image), it is not scale-invariant. If you zoom in significantly, a sharp corner might appear as a smooth, rounded edge, and the small sliding window will no longer detect it as a corner. Modern keypoint detectors like SIFT solve this by searching for features across multiple scales of the image (an image pyramid), ensuring that the keypoints can be matched even if the object is closer or further away from the camera.
Code
import numpy as npimport cv2
def detect_harris_corners(image_path: str) -> np.ndarray: # Read the image and convert to grayscale img = cv2.imread(image_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to float32 for cornerHarris function gray = np.float32(gray) # Calculate Harris corners: block size 2, aperture 3, k 0.04 dst = cv2.cornerHarris(gray, 2, 3, 0.04) # Dilate to mark the corners more visibly dst = cv2.dilate(dst, None) # Threshold for an optimal value to mark corners in red img[dst > 0.01 * dst.max()] = [0, 0, 255] # -> Returns image with corners marked return imgWatch Out For
Scale Variance in Simple Detectors
The standard Harris Corner Detector fails entirely if the scale of the object changes drastically between images. A corner detected in a zoomed-out image will look like a soft curve in a zoomed-in image. If you need to match keypoints across different zoom levels, you must use a scale-invariant detector like SIFT or ORB instead.
Repetitive Patterns and Aliasing
Keypoint detectors struggle significantly with highly repetitive patterns, such as a brick wall or a chessboard. A corner detector will fire thousands of times on a brick wall, but because every brick looks identical locally, a matching algorithm downstream will have no idea which corner in Image A corresponds to which corner in Image B.
The Quick Version
- Keypoints are highly distinct, localizable features in an image used for tracking and matching across frames.
- Corners are ideal keypoints because they exhibit high contrast changes in all directions, unlike flat regions or edges.
- The Harris Corner Detector uses image gradients to build a Structure Tensor, identifying corners by looking for regions with two large eigenvalues.
- Basic corner detectors are rotation-invariant but fail when the image is scaled (zoomed in or out).
- Advanced algorithms like SIFT introduce scale invariance by detecting features across multiple resolutions.