Python convert JPEG bytes to image array
Question:
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:UsersmartiPicturesDesktopscriptsCAMIMG.jpg', 'JPEG') #SAVE
frame = cv2.imread(r'C:UsersmartiPicturesDesktopscriptsCAMIMG.jpg') #OPEN
cv2.imshow("dfsdf",frame)
cv2.destroyAllWindows
Answers:
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)
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:UsersmartiPicturesDesktopscriptsCAMIMG.jpg', 'JPEG') #SAVE
frame = cv2.imread(r'C:UsersmartiPicturesDesktopscriptsCAMIMG.jpg') #OPEN
cv2.imshow("dfsdf",frame)
cv2.destroyAllWindows
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)