Last updated: Apr 13, 2024
Reading time·2 min

To solve the OpenCV "TypeError: Expected cv::UMat for argument", make sure your image is of the correct form.
The first thing you should try is to pass the cv2.UMat object directly to
cv2.cvtColor().
import cv2 img = cv2.imread('thumbnail.webp') img_UMat = cv2.UMat(img) gray_UMat = cv2.cvtColor(img_UMat, cv2.COLOR_RGB2GRAY) print(gray_UMat)

The first argument the cv2.cvtColor() method takes is the image src.
If that doesn't work, try to convert the image to a NumPy array by passing it to numpy.array().
First, make sure you
have the numpy module installed.
pip install numpy # or with pip3 pip3 install numpy
Now, import the numpy module and convert the image to a NumPy array.
import cv2 import numpy as np img = cv2.imread('thumbnail.webp') # ✅ Convert image to NumPy array img = np.array(img) img_UMat = cv2.UMat(img) gray_UMat = cv2.cvtColor(img_UMat, cv2.COLOR_RGB2GRAY) print(gray_UMat)

I only added this line to the code sample.
# ✅ Convert an image to a NumPy array img = np.array(img)
If that doesn't work, try to use the numpy.ascontiguousarray() method instead.
import cv2 import numpy as np img = cv2.imread('thumbnail.webp') # ✅ using numpy.ascontiguousarray() img = np.ascontiguousarray(img) img_UMat = cv2.UMat(img) gray_UMat = cv2.cvtColor( img_UMat, cv2.COLOR_RGB2GRAY ) print(gray_UMat)

If the error persists, try to reassign the image to a copy of itself by calling
img.copy().
import cv2 img = cv2.imread('thumbnail.webp') # ✅ Create a copy of the image img = img.copy() img_UMat = cv2.UMat(img) gray_UMat = cv2.cvtColor(img_UMat, cv2.COLOR_RGB2GRAY) print(gray_UMat)

Notice that we reassigned the value of the img variable to the result of
calling img.copy().
# ✅ Create a copy of the image img = img.copy()
cv2.UMat object to the cv2.UMat classIf the error persists, try to pass the cv2.UMat object to the cv2.UMat class
when calling cv2.cvtColor().
import cv2 img = cv2.imread('thumbnail.webp') img_UMat = cv2.UMat(img) gray_UMat = cv2.cvtColor( cv2.UMat(img_UMat), cv2.COLOR_RGB2GRAY ) print(gray_UMat)

The only line I changed is the following.
gray_UMat = cv2.cvtColor( cv2.UMat(img_UMat), cv2.COLOR_RGB2GRAY )
I passed the already-created cv2.UMat object to the cv2.UMat class when
calling cv2.cvtColor().
If you get one of the following OpenCV errors, click on the link and follow the instructions: