forked from FAR-Lab/Interactive-Lab-Hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tm_ppe_detection.py
79 lines (64 loc) · 2.03 KB
/
tm_ppe_detection.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
#This example is directly copied from the Tensorflow examples provided from the Teachable Machine.
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np
import cv2
import sys
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
img = None
webCam = False
if(len(sys.argv)>1 and not sys.argv[-1]== "noWindow"):
try:
print("I'll try to read your image");
img = cv2.imread(sys.argv[1])
if img is None:
print("Failed to load image file:", sys.argv[1])
except:
print("Failed to load the image are you sure that:", sys.argv[1],"is a path to an image?")
else:
try:
print("Trying to open the Webcam.")
cap = cv2.VideoCapture(0)
if cap is None or not cap.isOpened():
raise("No camera")
webCam = True
except:
print("Unable to access webcam.")
# Load the model
model = tensorflow.keras.models.load_model('keras_model.h5')
# Load Labels:
labels=[]
f = open("labels.txt", "r")
for line in f.readlines():
if(len(line)<1):
continue
labels.append(line.split(' ')[1].strip())
while(True):
if webCam:
ret, img = cap.read()
rows, cols, channels = img.shape
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
size = (224, 224)
img = cv2.resize(img, size, interpolation = cv2.INTER_AREA)
#turn the image into a numpy array
image_array = np.asarray(img)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
# Load the image into the array
data[0] = normalized_image_array
# run the inference
prediction = model.predict(data)
print("I think its a:",labels[np.argmax(prediction)])
if webCam:
if sys.argv[-1] == "noWindow":
cv2.imwrite('detected_out.jpg',img)
continue
cv2.imshow('detected (press q to quit)',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
cap.release()
break
else:
break
cv2.imwrite('detected_out.jpg',img)
cv2.destroyAllWindows()