cap-inspector 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cap_inspector/__init__.py +2 -0
- cap_inspector/cap_inspector.py +486 -0
- cap_inspector/server_grpc/__init__.py +2 -0
- cap_inspector/server_grpc/client.py +45 -0
- cap_inspector/server_grpc/client.pyi +42 -0
- cap_inspector/server_grpc/make_pyi.py +27 -0
- cap_inspector/server_grpc/server.py +55 -0
- cap_inspector/viewer.py +321 -0
- cap_inspector-0.1.0.dist-info/METADATA +150 -0
- cap_inspector-0.1.0.dist-info/RECORD +13 -0
- cap_inspector-0.1.0.dist-info/WHEEL +5 -0
- cap_inspector-0.1.0.dist-info/licenses/LICENSE +202 -0
- cap_inspector-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
"""赤色キャップの位置・傾斜に基づく開閉検査。"""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
import cv2
|
|
8
|
+
import numpy as np
|
|
9
|
+
from x_logger import XLogger
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CapInspector:
|
|
13
|
+
"""赤色キャップの検出・開閉判定を行うクラス。
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
current_mode (str): inspect() の既定判定モード。
|
|
17
|
+
camera_id (int): 画像取得に使用するカメラ番号。
|
|
18
|
+
|
|
19
|
+
Notes:
|
|
20
|
+
コンストラクタ引数は初期値であり、個別setterで変更できる。
|
|
21
|
+
is_open() と is_closed() は直近の判定結果だけを返す。
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
camera_id=0,
|
|
27
|
+
BOTTLE_RIM_Y=275,
|
|
28
|
+
MM_TO_PIXEL=4.0,
|
|
29
|
+
TARGET_CLOSE_MM=0.5,
|
|
30
|
+
TARGET_OPEN_MM=3.5,
|
|
31
|
+
TOLERANCE_MM=1.0,
|
|
32
|
+
current_mode="closed",
|
|
33
|
+
logger=None,
|
|
34
|
+
):
|
|
35
|
+
self.camera_id = camera_id
|
|
36
|
+
self.BOTTLE_RIM_Y = BOTTLE_RIM_Y
|
|
37
|
+
self.MM_TO_PIXEL = MM_TO_PIXEL
|
|
38
|
+
self.TARGET_CLOSE_MM = TARGET_CLOSE_MM
|
|
39
|
+
self.TARGET_OPEN_MM = TARGET_OPEN_MM
|
|
40
|
+
self.TOLERANCE_MM = TOLERANCE_MM
|
|
41
|
+
self.current_mode = self._normalize_mode(current_mode)
|
|
42
|
+
if logger is None:
|
|
43
|
+
logger = XLogger(logger_name="cap_inspector")
|
|
44
|
+
self.logger = logger
|
|
45
|
+
self.cap = None
|
|
46
|
+
self._reset_detection()
|
|
47
|
+
self._is_safe = None
|
|
48
|
+
self._reason = None
|
|
49
|
+
self._last_frame = None
|
|
50
|
+
self._last_processed_frame = None
|
|
51
|
+
self._validate_parameters(self.get_parameters())
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def _normalize_mode(mode):
|
|
55
|
+
if mode == "open":
|
|
56
|
+
return "opened"
|
|
57
|
+
if mode not in ("closed", "opened"):
|
|
58
|
+
raise ValueError("mode must be 'closed' or 'opened' (or legacy 'open')")
|
|
59
|
+
return mode
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def mode(self):
|
|
63
|
+
return self.current_mode
|
|
64
|
+
|
|
65
|
+
@mode.setter
|
|
66
|
+
def mode(self, value):
|
|
67
|
+
self.current_mode = self._normalize_mode(value)
|
|
68
|
+
|
|
69
|
+
def _reset_detection(self):
|
|
70
|
+
self._box = None
|
|
71
|
+
self._bottom_points = None
|
|
72
|
+
self._lift_mm = None
|
|
73
|
+
self._tilt_angle = None
|
|
74
|
+
self._aspect_ratio = None
|
|
75
|
+
self._is_tilt_ok = None
|
|
76
|
+
self._result = False
|
|
77
|
+
self._is_open = False
|
|
78
|
+
self._is_closed = False
|
|
79
|
+
self._mode_str = None
|
|
80
|
+
self._detections = []
|
|
81
|
+
|
|
82
|
+
def __del__(self):
|
|
83
|
+
try:
|
|
84
|
+
self.stop_camera()
|
|
85
|
+
except Exception:
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
def start_camera(self):
|
|
89
|
+
if self.cap is not None and self.cap.isOpened():
|
|
90
|
+
return True
|
|
91
|
+
self.stop_camera()
|
|
92
|
+
self.cap = cv2.VideoCapture(self.camera_id)
|
|
93
|
+
if not self.cap.isOpened():
|
|
94
|
+
self.cap.release()
|
|
95
|
+
self.cap = None
|
|
96
|
+
self.logger.error(f"Camera open failed: camera_id={self.camera_id}")
|
|
97
|
+
return False
|
|
98
|
+
return True
|
|
99
|
+
|
|
100
|
+
def stop_camera(self):
|
|
101
|
+
if self.cap is not None:
|
|
102
|
+
self.cap.release()
|
|
103
|
+
self.cap = None
|
|
104
|
+
|
|
105
|
+
def release(self):
|
|
106
|
+
self.stop_camera()
|
|
107
|
+
|
|
108
|
+
def _read_frame(self):
|
|
109
|
+
if self.cap is None or not self.cap.isOpened():
|
|
110
|
+
if not self.start_camera():
|
|
111
|
+
raise RuntimeError(f"camera open failed: camera_id={self.camera_id}")
|
|
112
|
+
ret, frame = self.cap.read()
|
|
113
|
+
if not ret or frame is None:
|
|
114
|
+
raise RuntimeError("camera frame read failed")
|
|
115
|
+
return frame
|
|
116
|
+
|
|
117
|
+
def _detect_cap(self, frame):
|
|
118
|
+
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
|
|
119
|
+
lower_red1 = np.array([0, 120, 70])
|
|
120
|
+
upper_red1 = np.array([10, 255, 255])
|
|
121
|
+
lower_red2 = np.array([170, 120, 70])
|
|
122
|
+
upper_red2 = np.array([180, 255, 255])
|
|
123
|
+
mask = cv2.inRange(hsv, lower_red1, upper_red1) | cv2.inRange(
|
|
124
|
+
hsv, lower_red2, upper_red2
|
|
125
|
+
)
|
|
126
|
+
kernel = np.ones((5, 5), np.uint8)
|
|
127
|
+
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
|
|
128
|
+
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
|
129
|
+
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
|
130
|
+
return contours
|
|
131
|
+
|
|
132
|
+
def process_frame(self, frame, current_mode=None):
|
|
133
|
+
"""指定したフレームから開栓・閉栓の両条件を判定する。
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
frame: OpenCV BGR画像。
|
|
137
|
+
current_mode: 返却する判定結果のモード。省略時は現在の設定。
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
bool: 指定モードの条件を満たした場合は True。
|
|
141
|
+
|
|
142
|
+
Notes:
|
|
143
|
+
開栓・閉栓の判定フラグは同じフレームから同時に更新する。
|
|
144
|
+
"""
|
|
145
|
+
mode = self.current_mode
|
|
146
|
+
if current_mode is not None:
|
|
147
|
+
mode = self._normalize_mode(current_mode)
|
|
148
|
+
self._reset_detection()
|
|
149
|
+
self._is_safe = False
|
|
150
|
+
self._reason = "FAIL: Cap not detected"
|
|
151
|
+
self._last_frame = frame.copy()
|
|
152
|
+
self._last_processed_frame = None
|
|
153
|
+
if mode == "closed":
|
|
154
|
+
self._mode_str = f"Closed ({self.TARGET_CLOSE_MM:g}mm)"
|
|
155
|
+
else:
|
|
156
|
+
self._mode_str = f"Opened ({self.TARGET_OPEN_MM:g}mm)"
|
|
157
|
+
for cnt in self._detect_cap(frame):
|
|
158
|
+
if cv2.contourArea(cnt) <= 500:
|
|
159
|
+
continue
|
|
160
|
+
rect = cv2.minAreaRect(cnt)
|
|
161
|
+
box = np.intp(cv2.boxPoints(rect))
|
|
162
|
+
angle = rect[2]
|
|
163
|
+
w, h = rect[1]
|
|
164
|
+
if angle < -45:
|
|
165
|
+
angle += 90
|
|
166
|
+
w, h = h, w
|
|
167
|
+
tilt_angle = abs(angle)
|
|
168
|
+
if h > 0:
|
|
169
|
+
aspect_ratio = w / h
|
|
170
|
+
else:
|
|
171
|
+
aspect_ratio = 0
|
|
172
|
+
is_tilt_ok = tilt_angle < 3.0
|
|
173
|
+
if aspect_ratio < 2.3 or aspect_ratio > 2.8:
|
|
174
|
+
is_tilt_ok = False
|
|
175
|
+
bottom_points = sorted(box, key=lambda p: p[1], reverse=True)[:2]
|
|
176
|
+
cap_bottom_y = (bottom_points[0][1] + bottom_points[1][1]) / 2
|
|
177
|
+
lift_mm = (self.BOTTLE_RIM_Y - cap_bottom_y) / self.MM_TO_PIXEL
|
|
178
|
+
closed_result = bool(
|
|
179
|
+
is_tilt_ok
|
|
180
|
+
and abs(lift_mm - self.TARGET_CLOSE_MM) <= self.TOLERANCE_MM
|
|
181
|
+
)
|
|
182
|
+
open_result = bool(
|
|
183
|
+
is_tilt_ok
|
|
184
|
+
and abs(lift_mm - self.TARGET_OPEN_MM) <= self.TOLERANCE_MM
|
|
185
|
+
)
|
|
186
|
+
if mode == "closed":
|
|
187
|
+
result = closed_result
|
|
188
|
+
else:
|
|
189
|
+
result = open_result
|
|
190
|
+
detection = {
|
|
191
|
+
"box": box.tolist(),
|
|
192
|
+
"bottom_points": [point.tolist() for point in bottom_points],
|
|
193
|
+
"lift_mm": float(lift_mm),
|
|
194
|
+
"tilt_angle": float(tilt_angle),
|
|
195
|
+
"aspect_ratio": float(aspect_ratio),
|
|
196
|
+
"is_tilt_ok": bool(is_tilt_ok),
|
|
197
|
+
"result": result,
|
|
198
|
+
"is_open": open_result,
|
|
199
|
+
"is_closed": closed_result,
|
|
200
|
+
}
|
|
201
|
+
self._detections.append(detection)
|
|
202
|
+
# camera9_2 と同様に全輪郭を処理し、最後の有効輪郭を代表値とする。
|
|
203
|
+
self._box = box
|
|
204
|
+
self._bottom_points = bottom_points
|
|
205
|
+
self._lift_mm = float(lift_mm)
|
|
206
|
+
self._tilt_angle = float(tilt_angle)
|
|
207
|
+
self._aspect_ratio = float(aspect_ratio)
|
|
208
|
+
self._is_tilt_ok = bool(is_tilt_ok)
|
|
209
|
+
self._result = result
|
|
210
|
+
self._is_open = open_result
|
|
211
|
+
self._is_closed = closed_result
|
|
212
|
+
self._is_safe = result
|
|
213
|
+
if not is_tilt_ok:
|
|
214
|
+
self._reason = "FAIL: Cap tilt or aspect ratio"
|
|
215
|
+
elif not result:
|
|
216
|
+
self._reason = "FAIL: Cap position outside tolerance"
|
|
217
|
+
else:
|
|
218
|
+
self._reason = "OK"
|
|
219
|
+
return bool(self._result)
|
|
220
|
+
|
|
221
|
+
def inspect(self, current_mode=None):
|
|
222
|
+
"""カメラから1フレーム取得して検査する。
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
current_mode: ``closed`` または ``opened``。省略時は
|
|
226
|
+
インスタンスの現在のモードを使用する。指定時は設定も更新する。
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
bool: 指定モードの検査に合格した場合は True。
|
|
230
|
+
"""
|
|
231
|
+
if current_mode is not None:
|
|
232
|
+
self.current_mode = self._normalize_mode(current_mode)
|
|
233
|
+
return self.process_frame(self._read_frame())
|
|
234
|
+
|
|
235
|
+
def is_open(self) -> bool:
|
|
236
|
+
"""直近の検査で開栓条件を満たしたか返す。
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
bool: 最後のフレームで開栓条件を満たした場合は True。
|
|
240
|
+
未検査または検出失敗時は False。
|
|
241
|
+
|
|
242
|
+
Notes:
|
|
243
|
+
画像の取得や再判定は行わない。inspect() または
|
|
244
|
+
process_frame() で更新された状態を参照する。
|
|
245
|
+
"""
|
|
246
|
+
return self._is_open
|
|
247
|
+
|
|
248
|
+
def is_closed(self) -> bool:
|
|
249
|
+
"""直近の検査で閉栓条件を満たしたか返す。
|
|
250
|
+
|
|
251
|
+
Returns:
|
|
252
|
+
bool: 最後のフレームで閉栓条件を満たした場合は True。
|
|
253
|
+
未検査または検出失敗時は False。
|
|
254
|
+
"""
|
|
255
|
+
return self._is_closed
|
|
256
|
+
|
|
257
|
+
def is_safe(self):
|
|
258
|
+
"""直近の指定モードの検査結果を返す。画像取得は行わない。"""
|
|
259
|
+
return self._is_safe
|
|
260
|
+
|
|
261
|
+
def get_status(self):
|
|
262
|
+
"""直近の検査状態を取得する。再検査は行わない。"""
|
|
263
|
+
return {
|
|
264
|
+
"is_safe": self._is_safe,
|
|
265
|
+
"reason": self._reason,
|
|
266
|
+
"is_open": self._is_open,
|
|
267
|
+
"is_closed": self._is_closed,
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
def get_detection(self):
|
|
271
|
+
"""直近の代表検出結果をJSON互換の辞書で返す。"""
|
|
272
|
+
if not self._detections:
|
|
273
|
+
return None
|
|
274
|
+
return self._detections[-1].copy()
|
|
275
|
+
|
|
276
|
+
def get_detections(self):
|
|
277
|
+
return [item.copy() for item in self._detections]
|
|
278
|
+
|
|
279
|
+
def get_bottom_points(self):
|
|
280
|
+
if self._bottom_points is None:
|
|
281
|
+
return None
|
|
282
|
+
return self._bottom_points.tolist()
|
|
283
|
+
|
|
284
|
+
def get_box_shape(self):
|
|
285
|
+
if self._box is None:
|
|
286
|
+
return None
|
|
287
|
+
return self._box.tolist()
|
|
288
|
+
|
|
289
|
+
def get_lift_mm(self):
|
|
290
|
+
return self._lift_mm
|
|
291
|
+
|
|
292
|
+
def get_current_mode(self):
|
|
293
|
+
return self.current_mode
|
|
294
|
+
|
|
295
|
+
def get_camera_id(self):
|
|
296
|
+
return self.camera_id
|
|
297
|
+
|
|
298
|
+
def get_bottle_rim_y(self):
|
|
299
|
+
return self.BOTTLE_RIM_Y
|
|
300
|
+
|
|
301
|
+
def get_mm_to_PIXEL(self):
|
|
302
|
+
return self.MM_TO_PIXEL
|
|
303
|
+
|
|
304
|
+
def set_camera_id(self, camera_id):
|
|
305
|
+
self.set_parameters({"camera_id": camera_id})
|
|
306
|
+
|
|
307
|
+
def set_bottle_rim_y(self, value):
|
|
308
|
+
self.set_parameters({"BOTTLE_RIM_Y": value})
|
|
309
|
+
|
|
310
|
+
def set_mm_to_PIXEL(self, value):
|
|
311
|
+
self.set_parameters({"MM_TO_PIXEL": value})
|
|
312
|
+
|
|
313
|
+
def set_target_close_mm(self, value):
|
|
314
|
+
return self.set_parameters({"TARGET_CLOSE_MM": value})
|
|
315
|
+
|
|
316
|
+
def set_target_open_mm(self, value):
|
|
317
|
+
return self.set_parameters({"TARGET_OPEN_MM": value})
|
|
318
|
+
|
|
319
|
+
def set_tolerance_mm(self, value):
|
|
320
|
+
return self.set_parameters({"TOLERANCE_MM": value})
|
|
321
|
+
|
|
322
|
+
def set_mode(self, value):
|
|
323
|
+
return self.set_parameters({"mode": value})
|
|
324
|
+
|
|
325
|
+
def _draw_detections(self, frame):
|
|
326
|
+
for detection in self._detections:
|
|
327
|
+
box = np.asarray(detection["box"], dtype=np.intp)
|
|
328
|
+
bottom = detection["bottom_points"]
|
|
329
|
+
cv2.drawContours(frame, [box], 0, (0, 255, 0), 2)
|
|
330
|
+
cv2.line(frame, tuple(bottom[0]), tuple(bottom[1]), (0, 255, 255), 3)
|
|
331
|
+
cv2.line(
|
|
332
|
+
frame,
|
|
333
|
+
(0, int(self.BOTTLE_RIM_Y)),
|
|
334
|
+
(frame.shape[1], int(self.BOTTLE_RIM_Y)),
|
|
335
|
+
(255, 255, 0),
|
|
336
|
+
2,
|
|
337
|
+
)
|
|
338
|
+
label = (
|
|
339
|
+
f"[{self._mode_str}] Res:{detection['result']} "
|
|
340
|
+
f"({detection['lift_mm']:.1f}mm)"
|
|
341
|
+
)
|
|
342
|
+
cv2.putText(
|
|
343
|
+
frame, label, (int(box[0][0]), int(box[0][1]) - 10),
|
|
344
|
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2,
|
|
345
|
+
)
|
|
346
|
+
return frame
|
|
347
|
+
|
|
348
|
+
def get_image(self, jpeg_quality=85):
|
|
349
|
+
"""最新フレームを取得し、判定結果を描画したJPEGを返す。
|
|
350
|
+
|
|
351
|
+
Args:
|
|
352
|
+
jpeg_quality: JPEG品質(0~100)。
|
|
353
|
+
|
|
354
|
+
Returns:
|
|
355
|
+
dict: ``image``(JPEGバイト列)、``is_safe``、``reason``。
|
|
356
|
+
|
|
357
|
+
Notes:
|
|
358
|
+
画像ストリーミングも検査状態を更新する。GUIと制御スクリプトで
|
|
359
|
+
同じインスタンスを共有する場合は、状態更新の競合に注意する。
|
|
360
|
+
"""
|
|
361
|
+
frame = self._read_frame()
|
|
362
|
+
self.process_frame(frame)
|
|
363
|
+
processed = self._draw_detections(frame.copy())
|
|
364
|
+
self._last_processed_frame = processed.copy()
|
|
365
|
+
ok, encoded = cv2.imencode(
|
|
366
|
+
".jpg", processed, [int(cv2.IMWRITE_JPEG_QUALITY), int(jpeg_quality)]
|
|
367
|
+
)
|
|
368
|
+
if not ok:
|
|
369
|
+
raise RuntimeError("JPEG encoding failed")
|
|
370
|
+
return {
|
|
371
|
+
"image": encoded.tobytes(),
|
|
372
|
+
"is_safe": bool(self._is_safe),
|
|
373
|
+
"reason": self._reason,
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
def image_stream(self, jpeg_quality=85, interval_sec=0.1):
|
|
377
|
+
try:
|
|
378
|
+
while True:
|
|
379
|
+
yield self.get_image(jpeg_quality=jpeg_quality)
|
|
380
|
+
if interval_sec > 0:
|
|
381
|
+
time.sleep(float(interval_sec))
|
|
382
|
+
except GeneratorExit:
|
|
383
|
+
raise
|
|
384
|
+
|
|
385
|
+
def get_parameters(self):
|
|
386
|
+
return {
|
|
387
|
+
"camera_id": self.camera_id,
|
|
388
|
+
"BOTTLE_RIM_Y": self.BOTTLE_RIM_Y,
|
|
389
|
+
"MM_TO_PIXEL": self.MM_TO_PIXEL,
|
|
390
|
+
"TARGET_CLOSE_MM": self.TARGET_CLOSE_MM,
|
|
391
|
+
"TARGET_OPEN_MM": self.TARGET_OPEN_MM,
|
|
392
|
+
"TOLERANCE_MM": self.TOLERANCE_MM,
|
|
393
|
+
"mode": self.current_mode,
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
@classmethod
|
|
397
|
+
def _validate_parameters(cls, parameters):
|
|
398
|
+
cls._normalize_mode(parameters["mode"])
|
|
399
|
+
if float(parameters["MM_TO_PIXEL"]) <= 0:
|
|
400
|
+
raise ValueError("MM_TO_PIXEL must be positive")
|
|
401
|
+
if float(parameters["TOLERANCE_MM"]) < 0:
|
|
402
|
+
raise ValueError("TOLERANCE_MM must be nonnegative")
|
|
403
|
+
|
|
404
|
+
def set_parameters(self, parameters):
|
|
405
|
+
"""画像認識パラメータを一括更新する。
|
|
406
|
+
|
|
407
|
+
Args:
|
|
408
|
+
parameters (dict): 更新対象のパラメータ辞書。指定しない値は維持する。
|
|
409
|
+
|
|
410
|
+
Returns:
|
|
411
|
+
dict: 更新後の全パラメータ。
|
|
412
|
+
|
|
413
|
+
Raises:
|
|
414
|
+
ValueError: 未知のキー、または不正な設定値を受け取った場合。
|
|
415
|
+
"""
|
|
416
|
+
aliases = {"current_mode": "mode"}
|
|
417
|
+
allowed = set(self.get_parameters())
|
|
418
|
+
normalized = {}
|
|
419
|
+
for key, value in parameters.items():
|
|
420
|
+
normalized_key = aliases.get(key, key)
|
|
421
|
+
normalized[normalized_key] = value
|
|
422
|
+
unknown = set(normalized) - allowed
|
|
423
|
+
if unknown:
|
|
424
|
+
raise ValueError(f"unknown parameters: {sorted(unknown)}")
|
|
425
|
+
new = self.get_parameters()
|
|
426
|
+
new.update(normalized)
|
|
427
|
+
new["camera_id"] = int(new["camera_id"])
|
|
428
|
+
new["BOTTLE_RIM_Y"] = int(new["BOTTLE_RIM_Y"])
|
|
429
|
+
for key in ("MM_TO_PIXEL", "TARGET_CLOSE_MM", "TARGET_OPEN_MM", "TOLERANCE_MM"):
|
|
430
|
+
new[key] = float(new[key])
|
|
431
|
+
new["mode"] = self._normalize_mode(new["mode"])
|
|
432
|
+
self._validate_parameters(new)
|
|
433
|
+
camera_changed = new["camera_id"] != self.camera_id
|
|
434
|
+
if camera_changed:
|
|
435
|
+
self.stop_camera()
|
|
436
|
+
for key, value in new.items():
|
|
437
|
+
if key == "mode":
|
|
438
|
+
self.current_mode = value
|
|
439
|
+
else:
|
|
440
|
+
setattr(self, key, value)
|
|
441
|
+
return self.get_parameters()
|
|
442
|
+
|
|
443
|
+
def save_parameters(self, filename):
|
|
444
|
+
parameters = self.get_parameters()
|
|
445
|
+
with open(filename, "w", encoding="utf-8") as file:
|
|
446
|
+
json.dump(parameters, file, ensure_ascii=False, indent=2)
|
|
447
|
+
return parameters
|
|
448
|
+
|
|
449
|
+
def load_parameters(self, filename):
|
|
450
|
+
with open(filename, "r", encoding="utf-8") as file:
|
|
451
|
+
parameters = json.load(file)
|
|
452
|
+
return self.set_parameters(parameters)
|
|
453
|
+
|
|
454
|
+
def run(self):
|
|
455
|
+
"""camera9_2 と同等のキー操作・描画によるローカルテスト。"""
|
|
456
|
+
current_mode = "closed"
|
|
457
|
+
if not self.start_camera():
|
|
458
|
+
raise RuntimeError(f"camera open failed: camera_id={self.camera_id}")
|
|
459
|
+
print("=== 操作方法 ===")
|
|
460
|
+
print("'c' キー: 閉まっているかの判定モード (0.5mm) に切替")
|
|
461
|
+
print("'o' キー: 開いているかの判定モード (4.0mm) に切替")
|
|
462
|
+
print("'q' キー: 終了")
|
|
463
|
+
try:
|
|
464
|
+
while True:
|
|
465
|
+
ret, frame = self.cap.read()
|
|
466
|
+
if not ret or frame is None:
|
|
467
|
+
break
|
|
468
|
+
self.process_frame(frame, current_mode)
|
|
469
|
+
self._draw_detections(frame)
|
|
470
|
+
cv2.imshow("Webカメラ映像", frame)
|
|
471
|
+
key = cv2.waitKey(1) & 0xFF
|
|
472
|
+
if key == ord("q"):
|
|
473
|
+
break
|
|
474
|
+
if key == ord("c"):
|
|
475
|
+
current_mode = "closed"
|
|
476
|
+
print("-> 【閉まっているか】の判定モード (0.5mm) に切り替えました")
|
|
477
|
+
elif key == ord("o"):
|
|
478
|
+
current_mode = "opened"
|
|
479
|
+
print("-> 【開いているか】の判定モード (4.0mm) に切り替えました")
|
|
480
|
+
finally:
|
|
481
|
+
self.stop_camera()
|
|
482
|
+
cv2.destroyAllWindows()
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
if __name__ == "__main__":
|
|
486
|
+
CapInspector().run()
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from grpc_frame.grpc_client import GrpcClient
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CapInspectorClient(GrpcClient):
|
|
7
|
+
"""CapInspector 用 gRPC クライアント。
|
|
8
|
+
|
|
9
|
+
grpc_frame の動的 API をそのまま利用しつつ、クライアントの用途を
|
|
10
|
+
CapInspector に限定して明確にするためのクラス。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, host="127.0.0.1", port=50051, grpc_options=None):
|
|
14
|
+
if grpc_options is None:
|
|
15
|
+
grpc_options = (("grpc.max_receive_message_length", 16 * 1024 * 1024),)
|
|
16
|
+
super().__init__(host, port, grpc_options=grpc_options)
|
|
17
|
+
|
|
18
|
+
# GrpcClient.__init__() は Describe の結果から同名メソッドを
|
|
19
|
+
# インスタンス属性として動的バインドする。image_stream は通常の
|
|
20
|
+
# Call ではなく StreamCall を使う必要があるため、その動的バインドを
|
|
21
|
+
# 除去して、このクラスで定義した image_stream() を有効にする。
|
|
22
|
+
for method_name in (
|
|
23
|
+
"image_stream",
|
|
24
|
+
"save_parameters",
|
|
25
|
+
"load_parameters",
|
|
26
|
+
):
|
|
27
|
+
if method_name in self.__dict__:
|
|
28
|
+
del self.__dict__[method_name]
|
|
29
|
+
|
|
30
|
+
def save_parameters(self, filename: str):
|
|
31
|
+
"""serverの現在値を取得し、client側ファイルへ保存する。"""
|
|
32
|
+
parameters = self.get_parameters()
|
|
33
|
+
with open(filename, "w", encoding="utf-8") as file:
|
|
34
|
+
json.dump(parameters, file, ensure_ascii=False, indent=2)
|
|
35
|
+
return parameters
|
|
36
|
+
|
|
37
|
+
def load_parameters(self, filename: str):
|
|
38
|
+
"""client側ファイルを読み込み、serverへ認識パラメータを設定する。"""
|
|
39
|
+
with open(filename, "r", encoding="utf-8") as file:
|
|
40
|
+
parameters = json.load(file)
|
|
41
|
+
return self.set_parameters(parameters)
|
|
42
|
+
|
|
43
|
+
def image_stream(self, jpeg_quality: int = 85, interval_sec: float = 0.1):
|
|
44
|
+
"""画像ストリームを server-streaming RPC で取得する。"""
|
|
45
|
+
return self.stream_call("image_stream", jpeg_quality, interval_sec)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from typing import Any, Optional, Union, Dict, List, Tuple, Callable, Sequence
|
|
2
|
+
|
|
3
|
+
class CapInspectorClient:
|
|
4
|
+
def __init__(self, host: Any = ..., port: Any = ..., grpc_options: Any = ...) -> None: ...
|
|
5
|
+
def save_parameters(self, filename: str) -> Any: ...
|
|
6
|
+
def load_parameters(self, filename: str) -> Any: ...
|
|
7
|
+
def image_stream(self, jpeg_quality: int = ..., interval_sec: float = ...) -> Any: ...
|
|
8
|
+
def wait_for_ready(self, timeout_sec: float = ...) -> bool: ...
|
|
9
|
+
def is_connected(self) -> bool: ...
|
|
10
|
+
def stream_call(self, method_name: str, *args: Any, **kwargs: Any) -> Any: ...
|
|
11
|
+
def close(self) -> None: ...
|
|
12
|
+
def subscribe(self, *, topic: str, once: bool = ..., source: str = ...) -> Any: ...
|
|
13
|
+
def mode(self) -> Any: ...
|
|
14
|
+
def start_camera(self) -> Any: ...
|
|
15
|
+
def stop_camera(self) -> Any: ...
|
|
16
|
+
def release(self) -> Any: ...
|
|
17
|
+
def process_frame(self, frame: Any, current_mode: Any = ...) -> Any: ...
|
|
18
|
+
def inspect(self, current_mode: Any = ...) -> Any: ...
|
|
19
|
+
def is_open(self, frame: Any = ...) -> Any: ...
|
|
20
|
+
def is_closed(self, frame: Any = ...) -> Any: ...
|
|
21
|
+
def is_safe(self) -> Any: ...
|
|
22
|
+
def get_status(self) -> Any: ...
|
|
23
|
+
def get_detection(self) -> Any: ...
|
|
24
|
+
def get_detections(self) -> Any: ...
|
|
25
|
+
def get_bottom_points(self) -> Any: ...
|
|
26
|
+
def get_box_shape(self) -> Any: ...
|
|
27
|
+
def get_lift_mm(self) -> Any: ...
|
|
28
|
+
def get_current_mode(self) -> Any: ...
|
|
29
|
+
def get_camera_id(self) -> Any: ...
|
|
30
|
+
def get_bottle_rim_y(self) -> Any: ...
|
|
31
|
+
def get_mm_to_PIXEL(self) -> Any: ...
|
|
32
|
+
def set_camera_id(self, camera_id: Any) -> Any: ...
|
|
33
|
+
def set_bottle_rim_y(self, value: Any) -> Any: ...
|
|
34
|
+
def set_mm_to_PIXEL(self, value: Any) -> Any: ...
|
|
35
|
+
def set_target_close_mm(self, value: Any) -> Any: ...
|
|
36
|
+
def set_target_open_mm(self, value: Any) -> Any: ...
|
|
37
|
+
def set_tolerance_mm(self, value: Any) -> Any: ...
|
|
38
|
+
def set_mode(self, value: Any) -> Any: ...
|
|
39
|
+
def get_image(self, jpeg_quality: Any = ...) -> Any: ...
|
|
40
|
+
def get_parameters(self) -> Any: ...
|
|
41
|
+
def set_parameters(self, parameters: Any) -> Any: ...
|
|
42
|
+
def run(self) -> Any: ...
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
"""grpc_frame の既存 API で CapInspectorClient の .pyi を生成する。"""
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import grpc_frame
|
|
7
|
+
from grpc_frame.make_pyi import generate_client_pyi
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main() -> None:
|
|
11
|
+
server_grpc_dir = Path(__file__).resolve().parent
|
|
12
|
+
package_dir = server_grpc_dir.parent
|
|
13
|
+
grpc_frame_dir = Path(grpc_frame.__file__).resolve().parent
|
|
14
|
+
|
|
15
|
+
generate_client_pyi(
|
|
16
|
+
client_py=server_grpc_dir / "client.py",
|
|
17
|
+
client_class="CapInspectorClient",
|
|
18
|
+
ctrl_py=package_dir / "cap_inspector.py",
|
|
19
|
+
ctrl_class="CapInspector",
|
|
20
|
+
base_py=grpc_frame_dir / "grpc_client.py",
|
|
21
|
+
base_class="GrpcClient",
|
|
22
|
+
out_path=server_grpc_dir / "client.pyi",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
if __name__ == "__main__":
|
|
27
|
+
main()
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from typing import Any, Optional, Sequence, Tuple
|
|
2
|
+
|
|
3
|
+
from grpc_frame.grpc_server import create_grpc_server
|
|
4
|
+
|
|
5
|
+
from cap_inspector.cap_inspector import CapInspector
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def cap_inspector_server(
|
|
9
|
+
*,
|
|
10
|
+
grpc_host: str,
|
|
11
|
+
grpc_port: int,
|
|
12
|
+
camera_id: int = 0,
|
|
13
|
+
inspector_parameters: Optional[dict] = None,
|
|
14
|
+
grpc_options: Optional[Sequence[Tuple[str, Any]]] = None,
|
|
15
|
+
logger: Optional[Any] = None,
|
|
16
|
+
) -> None:
|
|
17
|
+
"""CapInspector を grpc_frame 上で公開するサーバーを起動する。"""
|
|
18
|
+
if grpc_options is None:
|
|
19
|
+
grpc_options = (
|
|
20
|
+
("grpc.max_send_message_length", 16 * 1024 * 1024),
|
|
21
|
+
("grpc.max_receive_message_length", 16 * 1024 * 1024),
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
parameters = {"camera_id": camera_id}
|
|
25
|
+
if inspector_parameters is not None:
|
|
26
|
+
parameters.update(inspector_parameters)
|
|
27
|
+
cap = CapInspector(logger=logger, **parameters)
|
|
28
|
+
server = create_grpc_server(
|
|
29
|
+
ctrl_obj=cap,
|
|
30
|
+
stream_obj=cap,
|
|
31
|
+
grpc_options=grpc_options,
|
|
32
|
+
logger=logger,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
address = str(grpc_host) + ":" + str(grpc_port)
|
|
36
|
+
ret = server.add_insecure_port(address)
|
|
37
|
+
if ret == 0:
|
|
38
|
+
cap.release()
|
|
39
|
+
raise RuntimeError("bind failed: " + address)
|
|
40
|
+
|
|
41
|
+
if logger is not None:
|
|
42
|
+
logger.info("CapInspector server started: " + address)
|
|
43
|
+
|
|
44
|
+
server.start()
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
server.wait_for_termination()
|
|
48
|
+
except KeyboardInterrupt:
|
|
49
|
+
if logger is not None:
|
|
50
|
+
logger.info("Server stop requested by keyboard interrupt")
|
|
51
|
+
finally:
|
|
52
|
+
server.stop(grace=None)
|
|
53
|
+
cap.release()
|
|
54
|
+
if logger is not None:
|
|
55
|
+
logger.info("CapInspector server shutdown completed")
|