forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathharris_corner.py
71 lines (61 loc) · 2.16 KB
/
harris_corner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
importcv2
importnumpyasnp
"""
Harris Corner Detector
https://en.wikipedia.org/wiki/Harris_Corner_Detector
"""
classHarrisCorner:
def__init__(self, k: float, window_size: int):
"""
k : is an empirically determined constant in [0.04,0.06]
window_size : neighbourhoods considered
"""
ifkin (0.04, 0.06):
self.k=k
self.window_size=window_size
else:
raiseValueError("invalid k value")
def__str__(self) ->str:
returnstr(self.k)
defdetect(self, img_path: str) ->tuple[cv2.Mat, list[list[int]]]:
"""
Returns the image with corners identified
img_path : path of the image
output : list of the corner positions, image
"""
img=cv2.imread(img_path, 0)
h, w=img.shape
corner_list: list[list[int]] = []
color_img=img.copy()
color_img=cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB)
dy, dx=np.gradient(img)
ixx=dx**2
iyy=dy**2
ixy=dx*dy
k=0.04
offset=self.window_size//2
foryinrange(offset, h-offset):
forxinrange(offset, w-offset):
wxx=ixx[
y-offset : y+offset+1, x-offset : x+offset+1
].sum()
wyy=iyy[
y-offset : y+offset+1, x-offset : x+offset+1
].sum()
wxy=ixy[
y-offset : y+offset+1, x-offset : x+offset+1
].sum()
det= (wxx*wyy) - (wxy**2)
trace=wxx+wyy
r=det-k* (trace**2)
# Can change the value
ifr>0.5:
corner_list.append([x, y, r])
color_img.itemset((y, x, 0), 0)
color_img.itemset((y, x, 1), 0)
color_img.itemset((y, x, 2), 255)
returncolor_img, corner_list
if__name__=="__main__":
edge_detect=HarrisCorner(0.04, 3)
color_img, _=edge_detect.detect("path_to_image")
cv2.imwrite("detect.png", color_img)