Home > Mobile >  Python convert JPEG bytes to image for OpenCV
Python convert JPEG bytes to image for OpenCV

Time:06-26

How can i pass row jpg data to OpenCV i have a code that saves the image and then opens it again but that is too slow, 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

CodePudding user response:

To answer your initial question, you could do

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",frame)

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

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)
  • Related