-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcomputer_vision.py
More file actions
168 lines (135 loc) Β· 5.67 KB
/
computer_vision.py
File metadata and controls
168 lines (135 loc) Β· 5.67 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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import cv2
import numpy as np
import tensorflow as tf
from tensorflow import keras
import os
import sys
import time
from threading import Thread
# Tambahan dari testing_webcam_external.py
class VideoStream:
def __init__(self, src):
self.stream = cv2.VideoCapture(src, cv2.CAP_FFMPEG)
self.stream.set(cv2.CAP_PROP_BUFFERSIZE, 1)
self.grabbed, self.frame = self.stream.read()
self.stopped = False
Thread(target=self.update, args=(), daemon=True).start()
def update(self):
while not self.stopped:
if self.stream.isOpened():
self.grabbed, self.frame = self.stream.read()
def read(self):
return self.frame
def stop(self):
self.stopped = True
self.stream.release()
class SimpleDetector:
def __init__(self, model_path="data/keras_model.h5", labels_path="data/labels.txt", confidence_threshold=0.8):
self.model_path = model_path
self.labels_path = labels_path
self.confidence_threshold = confidence_threshold
self.input_shape = (224, 224)
self.class_names = []
self.start_time = None
self.detected = False
self.load_model()
self.load_labels()
def load_model(self):
try:
if not os.path.exists(self.model_path):
raise FileNotFoundError(f"Model file tidak ditemukan: {self.model_path}")
print("π Mencoba memuat model...")
print("π§ Mencoba perbaikan manual untuk parameter 'groups'...")
import tensorflow.keras.layers as layers
class FixedDepthwiseConv2D(layers.DepthwiseConv2D):
def __init__(self, **kwargs):
kwargs.pop('groups', None)
super().__init__(**kwargs)
custom_objects_fixed = {
'DepthwiseConv2D': FixedDepthwiseConv2D
}
self.model = keras.models.load_model(
self.model_path,
compile=False,
custom_objects=custom_objects_fixed
)
print(f"β
Model berhasil dimuat: {self.model_path}")
input_shape = self.model.input_shape
if len(input_shape) >= 3:
self.input_shape = (input_shape[1], input_shape[2])
print(f"π Input shape: {self.input_shape}")
print(f"π― Confidence threshold: {self.confidence_threshold:.0%}")
except Exception as e:
print(f"β Error loading model: {e}")
sys.exit(1)
def load_labels(self):
try:
if not os.path.exists(self.labels_path):
raise FileNotFoundError(f"Labels file tidak ditemukan: {self.labels_path}")
with open(self.labels_path, "r", encoding="utf-8") as f:
self.class_names = [line.strip() for line in f.readlines()]
print(f"β
Labels berhasil dimuat: {len(self.class_names)} kelas")
except Exception as e:
print(f"β Error loading labels: {e}")
sys.exit(1)
def preprocess(self, frame):
resized = cv2.resize(frame, self.input_shape)
rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
normalized = rgb.astype(np.float32) / 255.0
return np.expand_dims(normalized, axis=0)
def predict(self, frame):
processed = self.preprocess(frame)
predictions = self.model.predict(processed, verbose=0)
class_idx = np.argmax(predictions[0])
confidence = predictions[0][class_idx]
return self.class_names[class_idx], confidence
def stable_detect(self, frame, now):
label, conf = self.predict(frame)
if conf >= self.confidence_threshold:
if not hasattr(self, 'start_time') or self.start_time is None:
self.start_time = now
elif not hasattr(self, 'detected') or not self.detected:
if now - self.start_time >= 1.0:
self.detected = True
return label, conf, True # Deteksi stabil
else:
self.start_time = None
self.detected = False
return label, conf, False
def run(self, camera_index="rtsp://192.168.100.10:8554/mystream"):
vs = VideoStream(camera_index)
print("π₯ Deteksi dimulai. Tekan 'q' untuk keluar.")
start_time = None
detected = False
while True:
frame = vs.read()
if frame is None:
continue
label, conf = self.predict(frame)
now = time.time()
if conf >= self.confidence_threshold:
if start_time is None:
start_time = now
elif not detected and (now - start_time) >= 1.0:
print(f"β
Ikan terdeteksi: {label} ({conf:.1%})")
detected = True
else:
start_time = None
detected = False
# Tampilan
if conf >= self.confidence_threshold:
text = f"{label}: {conf:.1%}"
cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
else:
cv2.putText(frame, "π Mencari objek...", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (100, 100, 100), 2)
cv2.imshow("Deteksi Realtime", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
vs.stop()
cv2.destroyAllWindows()
if __name__ == "__main__":
if not os.path.exists("data/keras_model.h5") or not os.path.exists("data/labels.txt"):
print("β File model atau label tidak ditemukan.")
else:
detector = SimpleDetector("data/keras_model.h5", "data/labels.txt")
detector.run()