forked from ryoppippi/Gasyori100knock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
answer_65.py
139 lines (108 loc) · 3.7 KB
/
answer_65.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Zhang Suen thining algorythm
def Zhang_Suen_thining(img):
# get shape
H, W, C = img.shape
# prepare out image
out = np.zeros((H, W), dtype=np.int)
out[img[..., 0] > 0] = 1
# inverse
out = 1 - out
while True:
s1 = []
s2 = []
# step 1 ( rasta scan )
for y in range(1, H-1):
for x in range(1, W-1):
# condition 1
if out[y, x] > 0:
continue
# condition 2
f1 = 0
if (out[y-1, x+1] - out[y-1, x]) == 1:
f1 += 1
if (out[y, x+1] - out[y-1, x+1]) == 1:
f1 += 1
if (out[y+1, x+1] - out[y, x+1]) == 1:
f1 += 1
if (out[y+1, x] - out[y+1,x+1]) == 1:
f1 += 1
if (out[y+1, x-1] - out[y+1, x]) == 1:
f1 += 1
if (out[y, x-1] - out[y+1, x-1]) == 1:
f1 += 1
if (out[y-1, x-1] - out[y, x-1]) == 1:
f1 += 1
if (out[y-1, x] - out[y-1, x-1]) == 1:
f1 += 1
if f1 != 1:
continue
# condition 3
f2 = np.sum(out[y-1:y+2, x-1:x+2])
if f2 < 2 or f2 > 6:
continue
# condition 4
if out[y-1, x] + out[y, x+1] + out[y+1, x] < 1:
continue
# condition 5
if out[y, x+1] + out[y+1, x] + out[y, x-1] < 1:
continue
s1.append([y, x])
for v in s1:
out[v[0], v[1]] = 1
# step 2 ( rasta scan )
for y in range(1, H-1):
for x in range(1, W-1):
# condition 1
if out[y, x] > 0:
continue
# condition 2
f1 = 0
if (out[y-1, x+1] - out[y-1, x]) == 1:
f1 += 1
if (out[y, x+1] - out[y-1, x+1]) == 1:
f1 += 1
if (out[y+1, x+1] - out[y, x+1]) == 1:
f1 += 1
if (out[y+1, x] - out[y+1,x+1]) == 1:
f1 += 1
if (out[y+1, x-1] - out[y+1, x]) == 1:
f1 += 1
if (out[y, x-1] - out[y+1, x-1]) == 1:
f1 += 1
if (out[y-1, x-1] - out[y, x-1]) == 1:
f1 += 1
if (out[y-1, x] - out[y-1, x-1]) == 1:
f1 += 1
if f1 != 1:
continue
# condition 3
f2 = np.sum(out[y-1:y+2, x-1:x+2])
if f2 < 2 or f2 > 6:
continue
# condition 4
if out[y-1, x] + out[y, x+1] + out[y, x-1] < 1:
continue
# condition 5
if out[y-1, x] + out[y+1, x] + out[y, x-1] < 1:
continue
s2.append([y, x])
for v in s2:
out[v[0], v[1]] = 1
# if not any pixel is changed
if len(s1) < 1 and len(s2) < 1:
break
out = 1 - out
out = out.astype(np.uint8) * 255
return out
# Read image
img = cv2.imread("gazo.png").astype(np.float32)
# Zhang Suen thining
out = Zhang_Suen_thining(img)
# Save result
cv2.imwrite("out.png", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()