How to use image from PIL ImageGrab without saving it to a file?

Question:

I’m trying to compare the structural similarity of two images with the skimage package but it only works if use two images saved on my pc and not when I use an image created by ImageGrab from PIL even it’s basically the same image.

def structural_sim(img1, img2):
    sim, diff = structural_similarity(img1, img2, full=True)
    return sim

#doesn't work
tempScreen = ImageGrab.grab(bbox=(985,193,1895,704))

sim = structural_sim(tempScreen, cv2.imread('08-55-48.PNG', 0))

#works
tempScreen = ImageGrab.grab(bbox=(985,193,1895,704))
tempScreen.save("temp.PNG")

sim = structural_sim(cv2.imread('temp.PNG', 0), cv2.imread('08-55-48.PNG', 0))

The error is the following

AttributeError: shape. Did you mean: ‘save’?

How can I correctly use the result of ImageGrab.grab without using .save and then cv2.imread?

Asked By: Ferdi_ the_best

||

Answers:

Your question confuses me, but I think you want to get a Numpy array, like you would from cv2.imread() so that you can use it with scikit-image. But you currently have a PIL Image instead.

So, to get a Numpy array from a PIL Image, you need:

import numpy as np

na = np.array(YOUR_GRABBED_PILIMAGE)
Answered By: Mark Setchell