I'm creating a machine-learning program to recognize images that are shown on webcam. I've used Google Teachable Machine to generate the model and it works fine.
The matter I'm having issues with is printing the results of a prediction array, when an element of this array achieves a certain value (if it's equal to or more than 0.9 for an element, print a specific message).
Let's say when element prediction[0] >= 0.9 I want to execute print("Up") as it recognizes the image of an arrow facing up or if element prediction[1] >= 0.9 I'd do a print("Down") etc.
But when I try do that using the if statement I am presented with a
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I've tried to use any() and all() but that didn't help really.
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
# Load the model
model = tensorflow.keras.models.load_model('snake/keras_model.h5')
# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1.
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Capturing webcam frames ---------------------------------------------------------------------------------------
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
raise IOError("Cannot open webcam")
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, [224, 224], fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
cv2.imshow('Input', frame)
# Set webcam frame as an image for recognition
image = frame
# turn the image into a numpy array
image_array = np.asarray(image)
# 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)
if (prediction[0] >= 0.9):
print("Up")
elif (prediction[1] >= 0.9):
print("Down")
elif (prediction[2] >= 0.9):
print("Left")
elif (prediction[3] >= 0.9):
print("Right")
# print(prediction)
c = cv2.waitKey(1)
if c == 27:
break
cap.release()
cv2.destroyAllWindows()
prediction[0].shape
with aprint
statement and see if it's a scalar or an array.prediction.shape
orprediction[0].shape
?