0

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

PATHIK GHUGARE
  • 137
  • 1
  • 9
  • Hi. Look at https://stackoverflow.com/questions/21061814/how-can-i-read-an-image-from-an-internet-url-in-python-cv2-scikit-image-and-mah – script0 Dec 20 '21 at 17:23
  • While what you ask for can be achieved, did you actually profile how much time is spent downloading the image over the network vs. how much writing it to disk accounts for? – frippe Dec 20 '21 at 17:26
  • @frippe for some images it is taking like a minute or so and for some images around 2-3 seconds – PATHIK GHUGARE Dec 20 '21 at 17:46

1 Answers1

1

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
script0
  • 387
  • 2
  • 12
  • Thank you, it is working fine but we need to ```import urlib.request``` and instead of ```urlib.urlopen``` it should be ```urlib.request.urlopen``` – PATHIK GHUGARE Dec 20 '21 at 18:04