-1

How can i pass row jpg data to OpenCV? i have the code that saves the image and then opens it again but it is to slow for my purpes, does someone know how to do it without saving?

import requests
from PIL import Image
from io import BytesIO 
import cv2

while True:
    response = requests.get("https://www.cleverfiles.com/howto/wp-content/uploads/2018/03/minion.jpg", stream=True, allow_redirects=True)
    image = Image.open(BytesIO(response.content))
    image.save(r'C:\Users\marti\Pictures\Desktop\scripts\CAM\IMG.jpg', 'JPEG')    #SAVE
    frame = cv2.imread(r'C:\Users\marti\Pictures\Desktop\scripts\CAM\IMG.jpg')    #OPEN    
    cv2.imshow("dfsdf",frame)
cv2.destroyAllWindows
finix
  • 19
  • 7
  • 4
    Don't use PIL and OpenCV unnecessarily at the same time... you'll confuse yourself. You have a JPEG-encoded image already in `response.content`. Let OpenCV's `imdecode()` read from that. Have a read here... https://stackoverflow.com/a/66853311/2836621 – Mark Setchell Jun 26 '22 at 09:52

1 Answers1

2

To answer your initial question, you could do

import requests
from PIL import Image
import cv2
import numpy as np

url = "https://www.cleverfiles.com/howto/wp-content/uploads/2018/03/minion.jpg"
frame =  Image.open(requests.get(url, stream=True, allow_redirects=True).raw)
cv2.imshow("dfsdf", np.asarray(frame)[:,:,::-1])

But as per Mark's comment and this answer, you can skip PIL altogether:

import requests
import cv2
import numpy as np

url = "https://www.cleverfiles.com/howto/wp-content/uploads/2018/03/minion.jpg"

# Fetch JPEG data
d = requests.get(url)
# Decode in-memory, compressed JPEG into Numpy array
frame = cv2.imdecode(np.frombuffer(d.content,np.uint8), cv2.IMREAD_COLOR)
cv2.imshow("dfsdf",frame)
Keldorn
  • 1,980
  • 15
  • 25
  • 1
    this answer contains faulty code. `cv2.imshow` will not accept PIL Images. it only accepts numpy arrays. -- pass `np.asarray(frame)` instead... but be prepared to see strange colors because PIL uses RGB order while OpenCV expects BGR order, and interprets the data accordingly. – Christoph Rackwitz Jun 26 '22 at 12:11
  • Thanks @ChristophRackwitz, I fixed the code and added the corresponding imports. – Keldorn Jun 26 '22 at 14:38