How to use cv2.imread() with an image type object instead of "image path"?

Asked

Viewed 806 times

0

I wonder if there’s any way to do something like this:

import cv2, pyautogui

screenshot = pyautogui.screenshot()
cv2.imread(screenshot, 0)

Instead:

import cv2, pyautogui
screenshot = pyautogui.screenshot("imagem.png")
cv2.imread("imagem.png", 0)

2 answers

1

I didn’t quite understand the purpose, but if you want to simply save the image to use it again with Opencv, you can use the method save() of the image in this way:

pil_image = pyautogui.screenshot()
pil_image.save("<Nome_do_arquivo>")

image = cv2.imread("<Nome_do_arquivo>")

If what you want is to actually convert the image directly without saving to use with Opencv, the process will be a little more complicated and you will need to use the library numpy for that reason.

First, you must turn your image into an object of numpy.array and after that you should convert it from RGB to BGR. See below:

pil_image = pyautogui.screenshot()
image = numpy.array(pil_image)

# Converte de RGB para BGR
image = image[:, :, ::-1].copy()

cv2.imshow("Imagem", image)
  • A shortcut to . save would simply be: pyautogui.screenshot('<Nome_do_arquivo>') ;)

  • It was exactly the second example I needed. But I would also like to use cv2.imshow’s function to turn the image into Grayscale (cv2.imshow(img, 0). Is there any way to do this with numpy.array ?

  • 1

    @x8ss image is already the image in Opencv default, in BGR color space. Just convert image for the grayscale color space with the function cv2.cvtColor opencv.

0

Actually you don’t have to do anything.

take this test:

import cv2, pyautogui

screenshot = pyautogui.screenshot()
####### editado
img_opencv = cv2.imencode('.jpg', screenshot )[1].tostring()
####### editado
cv2.imshow("teste",img_opencv )
cv2.waitKey(0)

it will open a window with the print you took.

  • I needed imread() to be able to apply image recognition algorithms

  • ai q ta when you use pyautogui it already generates a jpg in a way that opencv understands but if you really need to force an image state does the same I edited it up there

  • then depending on the q vc will make him only convert to Gray or modify the size for neural network q vc to use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.