[python] OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Disclaimer: huge openCV noob

Traceback (most recent call last):

File "lanes2.py", line 22, in

canny = canny(lane_image)

File "lanes2.py", line 5, in canny

gray = cv2.cvtColor(imgUMat, cv2.COLOR_RGB2GRAY)

TypeError: Expected cv::UMat for argument 'src'

What exactly is 'src' referring to?

This question is related to python opencv typeerror src

The answer is


src is the first argument to cv2.cvtColor.

The error you are getting is because it is not the right form. cv2.Umat() is functionally equivalent to np.float32(), so your last line of code should read:

gray = cv2.cvtColor(np.float32(imgUMat), cv2.COLOR_RGB2GRAY)

gray = cv2.cvtColor(cv2.UMat(imgUMat), cv2.COLOR_RGB2GRAY)

UMat is a part of the Transparent API (TAPI) than help to write one code for the CPU and OpenCL implementations.


The following can be used from numpy:

import numpy as np 
image = np.array(image)

Not your code is the problem this is perfectly fine:

gray = cv2.cvtColor(imgUMat, cv2.COLOR_RGB2GRAY)

The problem is that imgUMat is None so you probably made a mistake when loading your image:

imgUMat = cv2.imread("your_image.jpg")

I suspect you just entered the wrong image path.


Some dtype are not supported by specific OpenCV functions. For example inputs of dtype np.uint32 create this error. Try to convert the input to a supported dtype (e.g. np.int32 or np.float32)


Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.


Just add this at start: image = cv2.imread(image)


This is a general error, which throws sometimes, when you have mismatch between the types of the data you use. E.g I tried to resize the image with opencv, it gave the same error. Here is a discussion about it.


I got round thid by writing/reading to a file. I guessed cv.imread would put it into the format it needed. This code for anki Vector SDK program but you get the idea.

tmpImage = robot.camera.latest_image.raw_image.save('temp.png')
pilImage = cv.imread('temp.png')


Sometimes I have this error when videostream from imutils package doesn't recognize frame or give an empty frame. In that case, solution will be figuring out why you have such a bad frame or use a standard VideoCapture(0) method from opencv2


that is referring to the expected dtype of your image
"image".astype('float32') should solve your issue


Questions with python tag:

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Upgrade to python 3.8 using conda Unable to allocate array with shape and data type How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip How to prevent Google Colab from disconnecting? "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? "E: Unable to locate package python-pip" on Ubuntu 18.04 Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' Jupyter Notebook not saving: '_xsrf' argument missing from post How to Install pip for python 3.7 on Ubuntu 18? Python: 'ModuleNotFoundError' when trying to import module from imported package OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website How to setup virtual environment for Python in VS Code? Pylint "unresolved import" error in Visual Studio Code Pandas Merging 101 Numpy, multiply array with scalar What is the meaning of "Failed building wheel for X" in pip install? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed Could not install packages due to an EnvironmentError: [Errno 13] OpenCV !_src.empty() in function 'cvtColor' error ConvergenceWarning: Liblinear failed to converge, increase the number of iterations How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How do I install opencv using pip? How do I install Python packages in Google's Colab? How do I use TensorFlow GPU? How to upgrade Python version to 3.7? How to resolve TypeError: can only concatenate str (not "int") to str How can I install a previous version of Python 3 in macOS using homebrew? Flask at first run: Do not use the development server in a production environment TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array What is the difference between Jupyter Notebook and JupyterLab? Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" How do I resolve a TesseractNotFoundError? Trying to merge 2 dataframes but get ValueError Authentication plugin 'caching_sha2_password' is not supported Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

Questions with opencv tag:

Real time face detection OpenCV, Python OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? OpenCV !_src.empty() in function 'cvtColor' error ConvergenceWarning: Liblinear failed to converge, increase the number of iterations How do I install opencv using pip? Access IP Camera in Python OpenCV ImportError: libSM.so.6: cannot open shared object file: No such file or directory Convert np.array of type float64 to type uint8 scaling values How to import cv2 in python3? cmake error 'the source does not appear to contain CMakeLists.txt' "Could not find a version that satisfies the requirement opencv-python" AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer' Python: How to pip install opencv2 with specific version 2.4.9? DLL load failed error when importing cv2 OpenCV - Saving images to a particular folder of choice OpenCV NoneType object has no attribute shape How do I increase the contrast of an image in Python OpenCV Normalizing images in OpenCV Pycharm/Python OpenCV and CV2 install error Opencv - Grayscale mode Vs gray color conversion OpenCV & Python - Image too big to display Python: how to capture image from webcam on click using OpenCV RuntimeError: module compiled against API version a but this version of numpy is 9 Python - Extracting and Saving Video Frames How to get image width and height in OpenCV? OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize" Writing an mp4 video using python opencv error: (-215) !empty() in function detectMultiScale open cv error: (-215) scn == 3 || scn == 4 in function cvtColor Loading all images using imread from a given folder openCV video saving in python How can I upgrade NumPy? OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow OpenCV in Android Studio How to convert a python numpy array to an RGB image with Opencv 2.4? Convert Mat to Array/Vector in OpenCV Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv Cannot get OpenCV to compile because of undefined references? How to draw a rectangle around a region of interest in python Extracting text OpenCV How do I install Python OpenCV through Conda? c++ and opencv get and set pixel color to Mat How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV Getting an error "fopen': This function or variable may be unsafe." when compling cv2.imshow command doesn't work properly in opencv-python How does one convert a grayscale image to RGB in OpenCV (Python)? Install opencv for Python 3.3 ImportError: numpy.core.multiarray failed to import Python+OpenCV: cv2.imwrite Cannot find module cv2 when using OpenCV

Questions with typeerror tag:

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Python TypeError must be str not int Uncaught TypeError: (intermediate value)(...) is not a function Slick Carousel Uncaught TypeError: $(...).slick is not a function Javascript Uncaught TypeError: Cannot read property '0' of undefined JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element' TypeError: 'list' object cannot be interpreted as an integer TypeError: unsupported operand type(s) for -: 'list' and 'list' I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer" Python sum() function with list parameter django: TypeError: 'tuple' object is not callable TypeError: not all arguments converted during string formatting python TypeError: unsupported operand type(s) for /: 'str' and 'str' TypeError: module.__init__() takes at most 2 arguments (3 given) TypeError: 'NoneType' object has no attribute '__getitem__' How to overcome TypeError: unhashable type: 'list' TypeError: $ is not a function when calling jQuery function "TypeError: (Integer) is not JSON serializable" when serializing JSON in Python? Python TypeError: not enough arguments for format string json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object? Javascript "Not a Constructor" Exception while creating objects super() raises "TypeError: must be type, not classobj" for new-style class "Uncaught TypeError: Illegal invocation" in Chrome Uncaught Typeerror: cannot read property 'innerHTML' of null TypeError: 'builtin_function_or_method' object is not subscriptable TypeError: coercing to Unicode: need string or buffer Uncaught TypeError: Cannot read property 'value' of undefined Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

Questions with src tag:

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Angular 4 img src is not found Rotate an image in image source in html html script src="" triggering redirection with button What is the right way to write my script 'src' url for a local development environment? How to properly reference local resources in HTML? Dynamically add script tag with src that may include document.write Programmatically change the src of an img tag Get img src with PHP Javascript : get <img> src and set as variable? Change image source with JavaScript jQuery attr() change img src src absolute path problem Why can't I do <img src="C:/localfile.jpg">? Changing iframe src with Javascript Pick images of root folder from sub-folder How to get the file-path of the currently executing javascript code Is it possible to set the equivalent of a src attribute of an img tag in CSS? Javascript set img src