2

I'm trying to use the following function:

def image_from_url(url):
    """
    Read an image from a URL. Returns a numpy array with the pixel data.
    We write the image to a temporary file then read it back. Kinda gross.
    """
    try:
        f = urllib.request.urlopen(url)
        _, fname = tempfile.mkstemp()
        with open(fname, 'wb') as ff:
            ff.write(f.read())
        img = imread(fname)
        os.remove(fname)
        return img
    except urllib.error.URLError as e:
        print('URL Error: ', e.reason, url)
    except urllib.error.HTTPError as e:
        print('HTTP Error: ', e.code, url)

But I keep on getting the following error:

---> 67         os.remove(fname)
     68         return img
     69     except urllib.error.URLError as e:
     PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\Nir\\AppData\\Local\\Temp\\tmp8p_pmso5'

No other processes are running on my machine (as far as I know). If I leave out the os.remove(fname) function, then the code works well, but I don't want my temp folder to fill up with garbage.

Any idea what is keeping the image from being deleted?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Nir Morgulis
  • 131
  • 1
  • 6

2 Answers2

1

I get the same error with you. I have uninstall my anaconda again and again, but still get the same error. Fortunately, I found out that this website(https://www.logilab.org/blogentry/17873) can solve my problem. Detailed description: modified:

try:
    f = urllib.request.urlopen(url)
    _, fname = tempfile.mkstemp()
    with open(fname, 'wb') as ff:
        ff.write(f.read())
    img = imread(fname)
    os.remove(fname)
    return img

to:

try:
    f = urllib.request.urlopen(url)
    fd, fname = tempfile.mkstemp()
    with open(fname, 'wb') as ff:
        ff.write(f.read())
    img = imread(fname)
    os.close(fd)
    os.remove(fname)
    return img
0

Have you tried TemporaryFile() etc? Is there a particular reason why you want to use mkstemp()? This kind of thing might work

with tempfile.NamedTemporaryFile('wb') as ff:
   ff.write(f.read())
   img = imread(ff.name)

PS you could read the image data into an array something like described here How do I read image data from a URL in Python?

import urllib, io
from PIL import Image
import numpy as np

file = io.BytesIO(urllib.request.urlopen(URL).read()) # edit to work on py3
a = np.array(Image.open(file))
paddyg
  • 2,153
  • 20
  • 24