How to solve ValueError: Negative dimension size caused by subtracting 3 from 1 for '{{node model/Conv1/Conv2D}} = Conv2D… in mobilenet_v2

datascience.stackexchange https://datascience.stackexchange.com/questions/86349

Question

I'm trying to apply a retrained model of mobilenet_v2 presented in https://github.com/balajisrinivas/Face-Mask-Detection

The main part of my adapted code is the following:

faces = []
locs = []
preds = []

for coord in coords:

    x = person[0]
    y = person[1]
    w = coord [2]
    h = person[3]

    # extract the face ROI, convert it from BGR to RGB channel
    # ordering, resize it to 224x224, and preprocess it
    face = frame[y:y+h, x:x+h]
    face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)

    if (face.shape) > (224, 224):
        face = cv.resize(face, (224, 224))
        
    face = img_to_array(face)
    face = preprocess_input(face) #from tensorflow.keras.applications.mobilenet_v2

    # add the face and bounding boxes to their respective lists
    faces.append(face)
    locs.append((x, y, w, h))

    # only make a predictions if at least one face was detected
    if len(faces) > 0:
        # for faster inference we'll make batch predictions on *all*
        # faces at the same time rather than one-by-one predictions
        faces = np.array(faces, dtype="float32")
        preds = maskNet.predict(faces, batch_size=32) #maskNet = load_model("mask_detector.model")

The error is raised when I try to apply maskNet.predict, which is the is the mobilenet_v2 model saved in https://github.com/balajisrinivas/Face-Mask-Detection/blob/master/mask_detector.model.

The error message is the following: ValueError: Negative dimension size caused by subtracting 3 from 1 for '{{node model/Conv1/Conv2D}} = Conv2D[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], explicit_paddings=[], padding="VALID", strides=[1, 2, 2, 1], use_cudnn_on_gpu=true](model/Conv1_pad/Pad, model/Conv1/Conv2D/ReadVariableOp)' with input shapes: [?,1,1,3], [3,3,3,32].

Was it helpful?

Solution

I found out my mistake!

I shouldn't use a condition before resizing the frame:

face = cv.resize(face, (224, 224)) #without if (face.shape) > (224, 224):

I've used the condition because I had to do that for SSD Resnet in the past, but I just realized it's not necessary for mobilenet_v2

Licensed under: CC-BY-SA with attribution
Not affiliated with datascience.stackexchange
scroll top