|
| 1 | +import numpy as np |
| 2 | +import cv2 |
| 3 | + |
| 4 | +""" |
| 5 | +Harris Corner Detector |
| 6 | +https://en.wikipedia.org/wiki/Harris_Corner_Detector |
| 7 | +""" |
| 8 | + |
| 9 | + |
| 10 | +class Harris_Corner: |
| 11 | + def __init__(self, k: float, window_size: int): |
| 12 | + |
| 13 | + """ |
| 14 | + k : is an empirically determined constant in [0.04,0.06] |
| 15 | + window_size : neighbourhoods considered |
| 16 | + """ |
| 17 | + |
| 18 | + if k in (0.04, 0.06): |
| 19 | + self.k = k |
| 20 | + self.window_size = window_size |
| 21 | + else: |
| 22 | + raise ValueError("invalid k value") |
| 23 | + |
| 24 | + def __str__(self): |
| 25 | + |
| 26 | + return f"Harris Corner detection with k : {self.k}" |
| 27 | + |
| 28 | + def detect(self, img_path: str): |
| 29 | + |
| 30 | + """ |
| 31 | + Returns the image with corners identified |
| 32 | + img_path : path of the image |
| 33 | + output : list of the corner positions, image |
| 34 | + """ |
| 35 | + |
| 36 | + img = cv2.imread(img_path, 0) |
| 37 | + h, w = img.shape |
| 38 | + corner_list = [] |
| 39 | + color_img = img.copy() |
| 40 | + color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) |
| 41 | + dy, dx = np.gradient(img) |
| 42 | + ixx = dx ** 2 |
| 43 | + iyy = dy ** 2 |
| 44 | + ixy = dx * dy |
| 45 | + k = 0.04 |
| 46 | + offset = self.window_size // 2 |
| 47 | + for y in range(offset, h - offset): |
| 48 | + for x in range(offset, w - offset): |
| 49 | + wxx = ixx[ |
| 50 | + y - offset : y + offset + 1, x - offset : x + offset + 1 |
| 51 | + ].sum() |
| 52 | + wyy = iyy[ |
| 53 | + y - offset : y + offset + 1, x - offset : x + offset + 1 |
| 54 | + ].sum() |
| 55 | + wxy = ixy[ |
| 56 | + y - offset : y + offset + 1, x - offset : x + offset + 1 |
| 57 | + ].sum() |
| 58 | + |
| 59 | + det = (wxx * wyy) - (wxy ** 2) |
| 60 | + trace = wxx + wyy |
| 61 | + r = det - k * (trace ** 2) |
| 62 | + # Can change the value |
| 63 | + if r > 0.5: |
| 64 | + corner_list.append([x, y, r]) |
| 65 | + color_img.itemset((y, x, 0), 0) |
| 66 | + color_img.itemset((y, x, 1), 0) |
| 67 | + color_img.itemset((y, x, 2), 255) |
| 68 | + return color_img, corner_list |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + |
| 73 | + edge_detect = Harris_Corner(0.04, 3) |
| 74 | + color_img, _ = edge_detect.detect("path_to_image") |
| 75 | + cv2.imwrite("detect.png", color_img) |
0 commit comments