Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Storing images from web into variable in Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading