-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetect.py
More file actions
269 lines (225 loc) · 9.13 KB
/
detect.py
File metadata and controls
269 lines (225 loc) · 9.13 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/env python3
"""
detect.py — Defect detection engine using TensorFlow Lite.
This module loads a trained TFLite model and classifies images
for manufacturing defects. Used by the Flask web app (app.py).
"""
import json
import os
import time
import numpy as np
from PIL import Image
class DefectDetector:
"""Loads a TFLite model and classifies images for defects."""
def __init__(self, model_dir="models"):
"""
Initialize the detector with a trained model.
Args:
model_dir: Directory containing defect_model.tflite,
labels.txt, and model_config.json
"""
self.model_dir = model_dir
self.model_path = os.path.join(model_dir, "defect_model.tflite")
self.labels_path = os.path.join(model_dir, "labels.txt")
self.config_path = os.path.join(model_dir, "model_config.json")
# Load model configuration
if os.path.exists(self.config_path):
with open(self.config_path, 'r') as f:
self.config = json.load(f)
self.image_size = self.config.get("image_size", 224)
self.class_names = self.config.get("class_names", [])
else:
self.image_size = 224
self.class_names = []
# Load labels (fallback)
if not self.class_names and os.path.exists(self.labels_path):
with open(self.labels_path, 'r') as f:
self.class_names = [line.strip() for line in f.readlines()]
# Load TFLite model
if os.path.exists(self.model_path):
self._load_model()
self.model_loaded = True
print(f"Model loaded: {self.model_path}")
print(f"Classes: {self.class_names}")
else:
self.model_loaded = False
print(f"WARNING: No model found at {self.model_path}")
print("Run train_model.py first to create a model.")
def _load_model(self):
"""Load the TFLite model and set up the interpreter."""
try:
# Try tflite_runtime first (lighter, preferred on Pi)
from tflite_runtime.interpreter import Interpreter
except ImportError:
# Fall back to full TensorFlow
from tensorflow.lite.python.interpreter import Interpreter
self.interpreter = Interpreter(model_path=self.model_path)
self.interpreter.allocate_tensors()
# Get input/output details
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
# Expected input shape
self.input_shape = self.input_details[0]['shape'] # e.g., [1, 224, 224, 3]
print(f"Model input shape: {self.input_shape}")
def preprocess_image(self, image_path):
"""
Load and preprocess an image for the model.
Args:
image_path: Path to the image file
Returns:
Preprocessed numpy array ready for inference
"""
img = Image.open(image_path).convert('RGB')
img = img.resize((self.image_size, self.image_size))
img_array = np.array(img, dtype=np.float32) / 255.0 # Normalize to 0-1
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
return img_array
def preprocess_frame(self, frame):
"""
Preprocess a camera frame (numpy array) for the model.
Args:
frame: OpenCV/picamera2 image array (BGR or RGB)
Returns:
Preprocessed numpy array ready for inference
"""
img = Image.fromarray(frame)
img = img.convert('RGB')
img = img.resize((self.image_size, self.image_size))
img_array = np.array(img, dtype=np.float32) / 255.0
img_array = np.expand_dims(img_array, axis=0)
return img_array
def predict(self, image_input):
"""
Run defect detection on an image.
Args:
image_input: Either a file path (str) or numpy array (frame)
Returns:
dict with keys:
- 'defect_type': Name of the detected class
- 'confidence': Confidence score (0.0 to 1.0)
- 'is_defective': True if defect detected (not 'good')
- 'all_scores': Dict of all class scores
- 'inference_time_ms': Time taken for inference
"""
if not self.model_loaded:
return {
'defect_type': 'unknown',
'confidence': 0.0,
'is_defective': False,
'all_scores': {},
'inference_time_ms': 0,
'error': 'No model loaded. Run train_model.py first.'
}
# Preprocess
if isinstance(image_input, str):
input_data = self.preprocess_image(image_input)
else:
input_data = self.preprocess_frame(image_input)
# Run inference
start_time = time.time()
self.interpreter.set_tensor(self.input_details[0]['index'], input_data)
self.interpreter.invoke()
output_data = self.interpreter.get_tensor(self.output_details[0]['index'])
inference_time = (time.time() - start_time) * 1000 # Convert to ms
# Process results
scores = output_data[0]
top_index = np.argmax(scores)
confidence = float(scores[top_index])
if top_index < len(self.class_names):
defect_type = self.class_names[top_index]
else:
defect_type = f"class_{top_index}"
# Build all scores dict
all_scores = {}
for i, score in enumerate(scores):
name = self.class_names[i] if i < len(self.class_names) else f"class_{i}"
all_scores[name] = round(float(score) * 100, 1) # Percentage
return {
'defect_type': defect_type,
'confidence': round(confidence, 4),
'confidence_pct': round(confidence * 100, 1),
'is_defective': defect_type.lower() != 'good',
'all_scores': all_scores,
'inference_time_ms': round(inference_time, 1)
}
class CameraCapture:
"""Handle camera capture on Raspberry Pi or fallback to webcam."""
def __init__(self, resolution=(640, 640)):
self.resolution = resolution
self.camera = None
self.use_picamera = False
try:
from picamera2 import Picamera2
self.camera = Picamera2()
config = self.camera.create_still_configuration(
main={"size": resolution, "format": "RGB888"}
)
self.camera.configure(config)
self.camera.start()
self.use_picamera = True
time.sleep(2)
print("Raspberry Pi Camera initialized")
except (ImportError, RuntimeError):
print("Pi Camera not available, trying webcam...")
try:
import cv2
self.camera = cv2.VideoCapture(0)
self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, resolution[0])
self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, resolution[1])
if self.camera.isOpened():
print("Webcam initialized")
else:
print("WARNING: No camera available!")
self.camera = None
except ImportError:
print("WARNING: Neither picamera2 nor OpenCV available!")
self.camera = None
def capture(self, save_path=None):
"""
Capture a single frame.
Args:
save_path: Optional path to save the captured image
Returns:
numpy array of the captured image, or None on failure
"""
if self.camera is None:
return None
if self.use_picamera:
frame = self.camera.capture_array()
else:
import cv2
ret, frame = self.camera.read()
if not ret:
return None
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if save_path and frame is not None:
img = Image.fromarray(frame)
img.save(save_path, quality=95)
return frame
def release(self):
"""Release camera resources."""
if self.camera is not None:
if self.use_picamera:
self.camera.stop()
else:
self.camera.release()
# --- Quick test ---
if __name__ == "__main__":
import sys
detector = DefectDetector()
if len(sys.argv) > 1:
# Test with a specific image
image_path = sys.argv[1]
if os.path.exists(image_path):
result = detector.predict(image_path)
print(f"\nResults for: {image_path}")
print(f" Defect type : {result['defect_type']}")
print(f" Confidence : {result['confidence_pct']}%")
print(f" Is defective: {result['is_defective']}")
print(f" Inference : {result['inference_time_ms']} ms")
print(f" All scores : {result['all_scores']}")
else:
print(f"File not found: {image_path}")
else:
print("\nUsage: python detect.py <image_path>")
print("Or import DefectDetector in your own code.")