PIL.Image to cv2: Expected Ptr<cv::UMat> for argument 'src'

Viewed 4740

I am using the pyautogui library to take a screenshot, which gets stored as PIL.Image.Image. When I try to use cv2's cvtColor() function to convert it, I get a TypeError:

TypeError: Expected Ptr<cv::UMat> for argument 'src'

Here is my code:

img = pyautogui.screenshot(0, 0, 500, 500)
print(type(img))    #<class 'PIL.Image.Image'>
img_rgb = numpy.array(img)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

What is my mistake here, and how could I convert the image as desired?

1 Answers

Never used the library, but from the error it gave out

try

img_gray = cv2.cvtColor(np.float32(img_rgb), cv2.COLOR_BGR2GRAY)

EDIT :

This is my test code which works fine

import pyautogui
import numpy as np
import cv2

img = pyautogui.screenshot(region=(0,0, 500, 500)) 
    #tested on impossible resolution as well, but the library still handles it. 
print(type(img))  #<class 'PIL.Image.Image'>
img_rgb = np.array(img) #<class 'numpy.ndarray'>
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
cv2.imshow("img",img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
Related