-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbar.py
More file actions
135 lines (102 loc) · 2.51 KB
/
Copy pathbar.py
File metadata and controls
135 lines (102 loc) · 2.51 KB
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
import cv2
import numpy as np
import os
# ---------------------------------------------------
# LOAD IMAGE
# ---------------------------------------------------
img = cv2.imread("374.bmp")
if img is None:
print("Image not found")
exit()
display = img.copy()
# ---------------------------------------------------
# OUTPUT
# ---------------------------------------------------
os.makedirs("bar_output", exist_ok=True)
# ---------------------------------------------------
# PREPROCESS
# ---------------------------------------------------
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Bright metal extraction
_, thresh = cv2.threshold(
gray,
180,
255,
cv2.THRESH_BINARY
)
# Morph cleanup
kernel = np.ones((3, 3), np.uint8)
thresh = cv2.morphologyEx(
thresh,
cv2.MORPH_OPEN,
kernel
)
# ---------------------------------------------------
# FIND CONTOURS
# ---------------------------------------------------
contours, _ = cv2.findContours(
thresh,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE
)
bar_index = 0
for cnt in contours:
area = cv2.contourArea(cnt)
if area < 1000:
continue
x, y, w, h = cv2.boundingRect(cnt)
aspect_ratio = h / float(w)
# ---------------------------------------------------
# STRICT BAR FILTER
# ---------------------------------------------------
# Tall vertical rectangle
if (
h > 120 and
w > 20 and
aspect_ratio > 2.0
):
# Ignore giant body regions
if w > 150:
continue
bar_index += 1
cv2.rectangle(
display,
(x, y),
(x + w, y + h),
(0, 255, 0),
3
)
cv2.putText(
display,
f"BAR {bar_index}",
(x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.8,
(0, 255, 0),
2
)
print(
f"BAR {bar_index}: "
f"x={x}, y={y}, w={w}, h={h}"
)
# ---------------------------------------------------
# SAVE OUTPUT
# ---------------------------------------------------
cv2.imwrite(
"bar_output/result.png",
display
)
cv2.imwrite(
"bar_output/thresh.png",
thresh
)
print("\nSaved:")
print("bar_output/result.png")
print("bar_output/thresh.png")
# ---------------------------------------------------
# SHOW
# ---------------------------------------------------
cv2.imshow("THRESH", thresh)
cv2.imshow("RESULT", display)
cv2.waitKey(0)
cv2.destroyAllWindows()