简体   繁体   中英

ValueError: Input 0 of layer sequential is incompatible with the layer(Reshape error)

This is my code:

import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import load_model

model=load_model('equation.h5')
############  prediction via paints ##########
### glob
run = False
ix, iy = -1, -1
follow = 25
img = np.zeros((512, 512, 1))

### func
def draw(event, x, y, flag, params):
    global run, ix, iy, img, follow
    if event == cv2.EVENT_LBUTTONDOWN:
        run = True
        ix, iy = x, y
    elif event == cv2.EVENT_MOUSEMOVE:
        if run == True:
            cv2.circle(img, (x, y), 20, (255, 255, 255), -1)

    elif event == cv2.EVENT_LBUTTONUP:
        run = False
        cv2.circle(img, (x, y), 20, (255, 255, 255), -1)
        gray = cv2.resize(img, (100,100))
        gray = gray.reshape(-1,100,100,1)
        result = np.argmax(model.predict(gray))
        result = 'cnn : {}'.format(result)
        file_object = open('sample.txt', 'a')
        # Append 'hello' at the end of file
        file_object.write(result +'\n')
        # Close the file
        file_object.close()
        cv2.putText(img, org=(25, follow), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, text=result,
                    color=(255, 0, 0), thickness=1)
        follow += 25
    elif event == cv2.EVENT_RBUTTONDOWN:
        img = np.zeros((512, 512, 1))
        follow = 25

### param
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw)

while True:
    cv2.imshow("image", img)

    if cv2.waitKey(1) == 27:
        break

cv2.destroyAllWindows()

I have created a model using mathematical symbols like +,-,= etc, the input shape of the model is (100, 100, 3). when I try to use that model it throws an error, the error is in reshaping, here an image is taken via OpenCV and it is resized and reshaped while reshapes it throws the below error:

C:\Users\Suganya\PycharmProjects\pythonProject1\venv\Scripts\python.exe C:/Users/Suganya/PycharmProjects/pythonProject1/digit.py
2021-05-02 11:27:53.306670: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2021-05-02 11:27:53.306939: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2021-05-02 11:27:55.277915: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
2021-05-02 11:27:55.278851: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found
2021-05-02 11:27:55.279077: W tensorflow/stream_executor/cuda/cuda_driver.cc:326] failed call to cuInit: UNKNOWN ERROR (303)
2021-05-02 11:27:55.282800: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: LAPTOP-OTIM27TH
2021-05-02 11:27:55.283095: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: LAPTOP-OTIM27TH
2021-05-02 11:27:55.283480: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2021-05-02 11:27:55.284291: I tensorflow/compiler/jit/xla_gpu_device.cc:99] Not creating XLA devices, tf_xla_enable_xla_devices not set
2021-05-02 11:27:57.000628: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2)
Traceback (most recent call last):
  File "C:/Users/Suganya/PycharmProjects/pythonProject1/digit.py", line 29, in draw
    result = np.argmax(model.predict(gray))
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1629, in predict
    tmp_batch_outputs = self.predict_function(iterator)
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\eager\def_function.py", line 828, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\eager\def_function.py", line 871, in _call
    self._initialize(args, kwds, add_initializers_to=initializers)
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\eager\def_function.py", line 726, in _initialize
    *args, **kwds))
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\eager\function.py", line 2969, in _get_concrete_function_internal_garbage_collected
    graph_function, _ = self._maybe_define_function(args, kwargs)
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\eager\function.py", line 3361, in _maybe_define_function
    graph_function = self._create_graph_function(args, kwargs)
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\eager\function.py", line 3206, in _create_graph_function
    capture_by_value=self._capture_by_value),
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\framework\func_graph.py", line 990, in func_graph_from_py_func
    func_outputs = python_func(*func_args, **func_kwargs)
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\eager\def_function.py", line 634, in wrapped_fn
    out = weak_wrapped_fn().__wrapped__(*args, **kwds)
  File "C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\framework\func_graph.py", line 977, in wrapper
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:

    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\keras\engine\training.py:1478 predict_function  *
        return step_function(self, iterator)
    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\keras\engine\training.py:1468 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1259 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2730 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3417 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\keras\engine\training.py:1461 run_step  **
        outputs = model.predict_step(data)
    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\keras\engine\training.py:1434 predict_step
        return self(x, training=False)
    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\keras\engine\base_layer.py:998 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    C:\Users\Suganya\PycharmProjects\pythonProject1\venv\lib\site-packages\tensorflow\python\keras\engine\input_spec.py:259 assert_input_compatibility
        ' but received input with shape ' + display_shape(x.shape))

    ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape (None, 100, 100, 1)

You say

the input shape of the model is (100,100,3)

but you are passing a grayscale image with shape (100,100,1) to the model.

Try modifying your image to RGB or, if you want to work with grayscale images, just use the same values on each of the 3 channels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM