0

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()
4
  • Check prediction[0].shape with a print statement and see if it's a scalar or an array. Commented Jun 10, 2021 at 16:26
  • print(prediction[0].shape) printed the following: (4,)
    – Matt
    Commented Jun 10, 2021 at 16:48
  • prediction.shape or prediction[0].shape? Commented Jun 10, 2021 at 16:55
  • print(prediction.shape) has returned (1, 4) print(prediction[0].shape) has returned (4,)
    – Matt
    Commented Jun 10, 2021 at 16:59

1 Answer 1

2

The problem is that your prediction has an "incorrect" shape when you're trying to check for each of the values. The following illustrates this:

import numpy as np

np.random.seed(5)

# Some random data    
prediction = np.random.uniform(low=0, high=1, size=(1, 4))

# This is what you have
>>> print(prediction.shape, prediction)
    (1, 4) [[0.22199317 0.87073231 0.20671916 0.91861091]]

# You have to access [0] first and then check the values
print(prediction[0].shape, prediction[0])
>>> (4,) [0.22199317 0.87073231 0.20671916 0.91861091]

So changing the indices of prediction in the conditions if prediction[0] > 0.9: ... to prediction[0, 0], prediction[0, 1], prediction[0, 2], etc. would solve your problem. Or simply doing prediction = model.predict(data)[0] and keeping the rest the same.

As a plus, you can create abbreviate your conditions by using np.where like so:

>>> prediction = prediction[0]
>>> corr = np.array(["Up", "Down", "Left", "Right"])
>>> print(prediction, corr[np.where(prediction >= 0.9)[0]])
    [0.22199317 0.87073231 0.20671916 0.91861091] ['Right']

>>> prediction[0] = 0.95
>>> print(prediction, corr[np.where(prediction >= 0.9)[0]])
    [0.95       0.87073231 0.20671916 0.91861091] ['Up' 'Right']
1
  • That has solved the problem! I didn't think that the array would have an incorrect shape. Thank you!
    – Matt
    Commented Jun 10, 2021 at 17:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.