Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display and close an image with Python?

I would like to display an image with Python and close it after user enters the name of the image in terminal. I use PIL to display image, here is the code:

im = Image.open("image.jpg")
im.show()

My application display this image, but user task is to recognize object on image and write answer in terminal. If answer entered is correct user should get another image. Problem with PIL is that I can't close the image and with research the only solution was to kill the process of image viewer, but this is not really reliable and elegant. Are there any other libraries for displaying images that have methods like .show() and .close() ?

like image 959
gorgi93 Avatar asked Nov 11 '12 01:11

gorgi93


Video Answer


2 Answers

A little late to the party, but (as a disgruntled data scientist who really can't be bothered to learn gui programming for the sake of displaying an image) I can probably speak for several other folks who would like to see an easier solution for this. I figured out a little work around by expanding Anurag's solution:

Make a second python script (let's call it 'imviewer.py'):

from skimage.viewer import ImageViewer
from skimage.io import imread

img = imread('image.png') #path to IMG
view = ImageViewer(img)
view.show()

Then in your main script do as Anurag suggested:

import subprocess
p = subprocess.Popen('python imviewer.py')
#your code
p.kill()

You can make the main script save the image you want to open with 'imviewer.py' temporarily, then overwrite it with the next image etc.

Hope this helps someone with this issue!

like image 79
Tristan HB Avatar answered Nov 01 '22 12:11

Tristan HB


Just open any image viewer/editor in a separate process and kill it once user has answered your question e.g.

from PIL import Image
import subprocess

p = subprocess.Popen(["display", "/tmp/test.png"])
raw_input("Give a name for image:")
p.kill()
like image 25
Anurag Uniyal Avatar answered Nov 01 '22 11:11

Anurag Uniyal