Skip to content

Instantly share code, notes, and snippets.

@lambdaofgod
Last active March 5, 2024 19:06
Show Gist options
  • Save lambdaofgod/d67445ee92b69d49343cdc34b7981490 to your computer and use it in GitHub Desktop.
Save lambdaofgod/d67445ee92b69d49343cdc34b7981490 to your computer and use it in GitHub Desktop.
Load image from url with requests using headers (this circumvents failing skimage.io.imread)
import requests
from PIL import Image
from io import BytesIO
import numpy as np
headers = {
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}
def load_image_bytes(url):
return requests.get(url, headers=headers).content
def content_to_ndarray(im_bytes):
bytes_io = bytearray(im_bytes)
img = Image.open(BytesIO(bytes_io))
return np.array(img)
def load_image_from_url(url):
return content_to_ndarray(load_image_bytes(url))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment