0

Using Google Colab, I would like to be able to read in some number of image files each of which is at a different url and then display each of them. I got the following code to work but it only displays the first image (no output for the 2nd or error messages) Also, if I add a print statement to the output, then no image display at all. So what's the trick? Thanks.

!pip install pillow
import urllib.request
from PIL import Image
# First Image
imageURL1 = "https://www.example.com/dir/imagefile1.jpg"
imageName1="file1.jpg"
urllib.request.urlretrieve(imageURL1, imageName1)
img1 = Image.open(imageName1)
img1  # this works but only if it is the only output
# Second Image
imageURL2 = "https://www.example.com/dir/imagefile2.jpg"
imageName2="file2.jpg"
urllib.request.urlretrieve(imageURL2, imageName2)
img2 = Image.open(imageName2)
img2 # does not display
#print("x") # a print kills the image display
Jim
  • 61
  • 9

1 Answers1

1

Found an answer that works. Use IPython to display the image. It works with multiple images and the print() works as well.

!pip install pillow
import urllib.request
from PIL import Image
from IPython.display import display

# First Image
imageURL1 = "https://www.example.com/dir/imagefile1.jpg"
imageName1="file1.jpg"
urllib.request.urlretrieve(imageURL1, imageName1)
img1 = Image.open(imageName1)
display(img1)  # this works but only if it is the only output

print("AND THE PRINT WORKS")

# Second Image
imageURL2 = "https://www.example.com/dir/imagefile2.jpg"
imageName2="file2.jpg"
urllib.request.urlretrieve(imageURL2, imageName2)
img2 = Image.open(imageName2)
display(img2)
Jim
  • 61
  • 9
  • There's no real need to write the file to disk, by the way. You can do `r=requests.get('...')` followed by `im=Image.open(io.BytesIO(r.content))` – Mark Setchell Jan 31 '23 at 21:00