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

3
  • Hi. Look at stackoverflow.com/questions/21061814/… Commented Dec 20, 2021 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? Commented Dec 20, 2021 at 17:26
  • @frippe for some images it is taking like a minute or so and for some images around 2-3 seconds Commented Dec 20, 2021 at 17:46

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it is working fine but we need to import urlib.request and instead of urlib.urlopen it should be urlib.request.urlopen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.