| 8 | |
| 9 | |
| 10 | class HarrisCorner: |
| 11 | def __init__(self, k: float, window_size: int): |
| 12 | """ |
| 13 | k : is an empirically determined constant in [0.04,0.06] |
| 14 | window_size : neighbourhoods considered |
| 15 | """ |
| 16 | |
| 17 | if k in (0.04, 0.06): |
| 18 | self.k = k |
| 19 | self.window_size = window_size |
| 20 | else: |
| 21 | raise ValueError("invalid k value") |
| 22 | |
| 23 | def __str__(self) -> str: |
| 24 | return str(self.k) |
| 25 | |
| 26 | def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: |
| 27 | """ |
| 28 | Returns the image with corners identified |
| 29 | img_path : path of the image |
| 30 | output : list of the corner positions, image |
| 31 | """ |
| 32 | |
| 33 | img = cv2.imread(img_path, 0) |
| 34 | h, w = img.shape |
| 35 | corner_list: list[list[int]] = [] |
| 36 | color_img = img.copy() |
| 37 | color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) |
| 38 | dy, dx = np.gradient(img) |
| 39 | ixx = dx**2 |
| 40 | iyy = dy**2 |
| 41 | ixy = dx * dy |
| 42 | k = 0.04 |
| 43 | offset = self.window_size // 2 |
| 44 | for y in range(offset, h - offset): |
| 45 | for x in range(offset, w - offset): |
| 46 | wxx = ixx[ |
| 47 | y - offset : y + offset + 1, x - offset : x + offset + 1 |
| 48 | ].sum() |
| 49 | wyy = iyy[ |
| 50 | y - offset : y + offset + 1, x - offset : x + offset + 1 |
| 51 | ].sum() |
| 52 | wxy = ixy[ |
| 53 | y - offset : y + offset + 1, x - offset : x + offset + 1 |
| 54 | ].sum() |
| 55 | |
| 56 | det = (wxx * wyy) - (wxy**2) |
| 57 | trace = wxx + wyy |
| 58 | r = det - k * (trace**2) |
| 59 | # Can change the value |
| 60 | if r > 0.5: |
| 61 | corner_list.append([x, y, r]) |
| 62 | color_img.itemset((y, x, 0), 0) |
| 63 | color_img.itemset((y, x, 1), 0) |
| 64 | color_img.itemset((y, x, 2), 255) |
| 65 | return color_img, corner_list |
| 66 | |
| 67 | |