opencv: BUG:TypeError: Expected Ptr for argument 'img'
- OpenCV =>3.10.37
- Operating System / Platform => Windows 64 Bit -python
import cv2
import sys
import numpy as np
import datetime
import os
import glob
import time
img = cv2.imread('t1.jpg')
# print(type(img))
img=np.rot90(img,-1)
# (h, w) = img.shape[:2] # 10
# center = (h // 2, w // 2) # 11
# M = cv2.getRotationMatrix2D(center, 90, 1.0) # 15
# img = cv2.warpAffine(img, M, (w, h)) # 16
color = (0, 0, 255)
print(img)
cv2.rectangle(img, (10,20 ),(30,40) ,color,2)
cv2.imwrite("5_flip.jpg",img)
When I ran this script, I encountered the following error:TypeError: Expected Ptrcv::UMat for argument ‘img’
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 18 (1 by maintainers)
Somehow
img = np.array(img)
still doesn’t work for me butimg = img.copy()
works.Just had this issue and resolved it by the explicit
img = np.array(img)
right before the operation that fails. It somehow helps even thoughtype(image_db)
returns<class 'numpy.ndarray'>
both before and after this line.@HanwenCao In my case the issue was in what was discussed in #15895. The bug appeared after flipping RGB to BGR with
img = img[:, :, ::-1]
. After replacing this line with the corresponding opencv operation like thisimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
I was able to get rid ofimg = np.array(img)
.Please refer to this comment for a better explanation of this behavior. Unfortunately, I wasn’t able to find what exactly “numpy on-the-fly reshaped array” means in a broader sense.
Just for the record:
change this " img = cv2.imread(‘t1.jpg’) " to " ret, img = cv2.imread(‘t1.jpg’) " may slove your problem.
Try to investigate using #15918
OpenCV can’t handle views as InputOutputArrays (there are several requirements for conversion).
Try to make regular numpy array:
np.ascontiguousarray
also help mitigate this issue.same as @louis925 , none of the other solutions worked for me but
img = img.copy()
did work. No idea why, because the dtype ofimg
for me was alreadyuint8
and the type wasnumpy.ndarray
.The command I was trying to run was
cv2.normalize(img, img, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
Note that changing the
dst
argument toNone
also fixed this issue. Very curious as to what’s causing this problem.When using
cv2.circle
I had to convert my 2D array using:img = np.array(img, dtype=np.uint8
to avoid this error.Great help.
img = np.array(img)
andimg=img[:,:,::-1]
both doesn’t work. Butimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
worked.You can use np.ascontiguousarray(img), for example in your case:
cv2.rectangle(np.ascontiguousarray(img), (10,20 ),(30,40) ,color,2)
In my case, using
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
afternp.rot90(img,-1)
works. However, just usingimg=np.array(np.rot90(img,-1))
doesn’t work.