Home > database >  Storing images from web into variable in Python
Storing images from web into variable in Python

Time:12-21

I have a lot of URLs of images stored on the web, example of a URL is as follows :

https://m.media-amazon.com/images/M/MV5BOWE4M2UwNWEtODFjOS00M2JiLTlhOGQtNTljZjI5ZTZlM2MzXkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_QL75_UX190_CR0

I want to load images from a similar URL as mentioned above and then do some operations on that image then return the resulting image.

So here's my code :

def get_image_from_url(url, path):
    try: 
        # downloading image from url
        img = requests.get(url)
        with open(path, 'wb') as f:
            f.write(img.content)

        # reading image, str(path) since path is object of Pathlib's path class
        img = cv2.imread(str(path), cv2.IMREAD_COLOR)

        # some operations 
        
        # deleting that downloaded image since it is of no use now   
        if os.path.exists(path):
            os.remove(path)

        return resulting_image
    except Exception as e:
        return np.zeros((224, 224, 3), np.uint8)

But this process is taking too much time so I thought instead of downloading and deleting the image I will directly load that image present on the URL into a variable.

Something like this :

def store_image_from_url(url):
    image = get_image_from_url(url) # without downloading it into my computer 

    # do some operations 

    return resulting_image

Is there any way to do the same?

Thank you

CodePudding user response:

As How can I read an image from an Internet URL in Python cv2, scikit image and mahotas?, it can be something like this :

import cv2
import urllib
import numpy as np

def get_image_from_url(url):
    req = urllib.urlopen(url)
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    img = cv2.imdecode(arr, -1)
    return img
  • Related