I'm trying to display an image using python. I used the following code :
from PIL import Image
img = Image.open("pic.jpg")
img.show()
del img
I checked that everything was installed, and tried different options inside the Image.open part, yet nothing works. I don't even have an error (so other topics were irrelevant in my case).
I am new to python, so I have no idea how to debug this. My code just executes but nothing happens.
If you have an idea, I'll try. Thank you.
You can get some information to debug your Python by changing your code to the following:
from PIL import Image
import subprocess
import sys
# Print the full path of the Python interpreter you are using
print(sys.executable)
# Print the working directory that your program is running in
subprocess.run('pwd')
# Print directory listing
# WINDOWS VERSION: subprocess.run('DIR')
subprocess.run(['ls', '-l'])
# Open the image
img = Image.open("pic.jpg")
# Check image loaded and its size and type
print(img)
# Display image
img.show()
# Check program ran to completion
print('Done')
Related
The objective is to receive an image path and pass that to a Python program as an argument, then receive the results.
This is done through a web app using VB (on the IIS server) and it works perfectly except when I import the python module OpenCV (imported in Python as cv2, more specifically).
What's even more confusing is that the script runs perfectly with the imported cv2 module when executed directly from cmd. It only fails to work when the VB code runs the script including the line import cv2.
I'll show some code below, for clarity.
VB code running Python script with image path as an argument:
Dim Processtask As New System.Diagnostics.Process()
Processtask.StartInfo.FileName = "cmd.exe"
Processtask.StartInfo.Arguments = "/c python " + path.ToString + " " + ImageURL.ToString
Processtask.StartInfo.UseShellExecute = False
Processtask.StartInfo.RedirectStandardOutput = True
Processtask.StartInfo.RedirectStandardError = True
Processtask.StartInfo.CreateNoWindow = True
Processtask.Start()
Processtask.WaitForExit()
output = Processtask.StandardOutput.ReadToEnd()
Python code snippet receiving image path:
import sys
import cv2
if __name__ == "__main__":
im = str(sys.argv[1])
print(im)
I have run out of possible ideas as to what could cause this problem. Any advice would be greatly appreciated.
EDIT
I managed to find the full error message which reads as follows:
System.Exception: System.IO.StreamReader
System.InvalidOperationException: Process has exited, so the requested
information is not available.
at System.Diagnostics.Process.EnsureState(State state) at
System.Diagnostics.Process.get_ProcessName()
at System.Diagnostics.Process.ToString()
Got the solution eventually, I'll post it here in case anyone else ever runs into this problem:
The dll files of opencv installed onto the server which hosted the web app had different access rights. The files were denied access when being called from the web application, whereas the rest of the modules called had no issue.
I used sysinternals process monitor to trace which files were being denied access and was able to change the rights by hand. Not very elegant but it worked out.
I am using PIL to open a single image in the default image viewer:
from PIL import Image
img = Image.open('example.jpg')
img.show()
Does any Python module contain a function enabling opening multiple images in the current system's default image viewer? For instance when on OS X, Preview.app should open with the list of images in the sidebar. From the command line this is no problem at all:
$ open my_picture_number_*
Use case is that users should just be able to explore a few dozen images.
Use subprocess.run to run the operating system's default image viewing app. subprocess.run works a lot like a command line. You just need to know what the command is for the operating system you're on. For windows, "explorer" will do; for OS X, as you point out, it's "open." I'm not sure what it is for Linux, maybe "eog"?
So, your code would look like this:
import sys
import subprocess
def openImage(path):
imageViewerFromCommandLine = {'linux':'xdg-open',
'win32':'explorer',
'darwin':'open'}[sys.platform]
subprocess.run([imageViewerFromCommandLine, path])
I've tried to use #jgfoot's answer, which worked, but made my program hang after the viewer was launched. I've solved this issue by using subprocess.Popen instead, like this:
import sys
import subprocess
def openImage(path):
imageViewerFromCommandLine = {'linux':'xdg-open',
'win32':'explorer',
'darwin':'open'}[sys.platform]
subprocess.Popen([imageViewerFromCommandLine, path])
I'm exceptionally new to python/scripting and I'm having a problem. I'm writing the following in Fiji (shortened version of the script is below...)
from ij import IJ, ImagePlus
from java.lang import Runtime, Runnable
import os
filepaths = []
for folder, subs, files in os.walk('location/of/files/'):
for filename in files:
#the next part stops it appending DS files
if not filename.startswith('.'):
filepaths.append(os.path.abspath(os.path.join(folder, filename,)))
for i in filepaths:
IJ.open(i);
IJ.close();
Basically I want to open an image, do stuff, and then close the processed image using IJ.close(). However it gives the following error:
AttributeError: type object 'ij.IJ' has no attribute 'close'
Any idea how to get around this?
Thanks!
The IJ class does not have a close() method. You probably want to call the close() method of ImagePlus, which is the class for the image objects themselves.
Try something like:
IJ.open(i)
imp = IJ.getImage()
imp.getProcessor().setf(100, 100, 3.14159) # or whatever
IJ.save(imp, "/path/to/myShinyModifiedImage.tif")
imp.close()
If you need to operate over multiple slices of a multi-plane image, see also the "Loop over slices" template (Templates > Python menu of the Script Editor).
Note also that Jython does not have trailing semicolons on statements.
For anyone else who is scripting with jython (python in ImageJ/Fiji), the Java docs always help in getting an overview of the modules and their classes/functions:
Here for example for the module ij
So basically I am trying to open an image and then close it after few seconds with time.sleep.
First I tried using
import Image
import time
myImage = Image.open("C:\\Users\\User\\Desktop\\image.jpg")
myImage.show()
time.sleep(5)
but this didn't work out well, since the image didn't even open because Windows Photo Viewer couldn't find the file. However when I use webbrowser.open like this
import webbrowser
webbrowser.open('C:\\Users\\User\\Desktop\\image.jpg')
webbrowser.close()
it successfully opens the file in Windows Photo Viewer, but closing doesn't seem to work. It gives me the following error:
AttributeError: 'module' object has no attribute 'close'
I've been searching for 2 days now with no working solution. The image is .jpg incase that matters. Also I don't want to change my default image viewer or modify things that other people who use this would have to modify as well. Using Python 2.7.
Any help would be very much appreciated!
This is my way to do it in windows_xp_sp3.
import os, time
pic=["C:\\19.jpg","C:\\20.jpg","C:\\21.jpg","C:\\22.jpg"]
for p in pic:
os.startfile(p)
time.sleep(3)
os.system("taskkill /IM rundll32.exe")
Or, try this:
import subprocess, time
pic=["C:\\19.jpg","C:\\20.jpg","C:\\21.jpg","C:\\22.jpg","C:\\23.jpg","C:\\24.jpg","C:\\25.jpg","C:\\26.jpg","C:\\27.jpg"]
for p in pic:
r=subprocess.Popen(p,shell=True)
time.sleep(3)
# r.kill() #It won't work, because "shell=True" is set.If you need to kill the "subprocess",just don't use it.
Like This:
import os,subprocess, time
pic=["C:\\19.jpg","C:\\20.jpg","C:\\21.jpg","C:\\22.jpg","C:\\23.jpg","C:\\24.jpg","C:\\25.jpg","C:\\26.jpg","C:\\27.jpg"]
for p in pic:
r=subprocess.Popen(["rundll32.exe","shimgvw.dll,ImageView_Fullscreen",p])
time.sleep(3)
r.kill()
You are on the wrong track here, to close it you would have to instruct the browser to close that tab, or window, or whatever.
The way to instruct a browser to do that, is not standardized, and the same holds for something which is different for each browser, or indeed for each photo viewer.
If you want to control both opening and closing of a photo, you are better off doing that from within your Python program, instead of calling upon a different program such as a browser.
Hi I'm trying to use a python gtk script under python 2.7.3; on Linux (under X11) and it needs to load images into pixbufs from disk.
However, python returns a glib.GError: "Couldn't recognize the image file format" regardless of what type of file I try to open;
eg: with: pixbuf = gtk.gdk.pixbuf_new_from_file( filename )
I can do a gtk.gdk.pixbuf_get_formats(), and in the list of dictionaries which is returned, the formats I have tried to load are listed .png, .ppm, .jpg.
When I try a gtk.gdk.pixbuf_get_file_info( filename ), though, it returns None.
Other GTK based programs such as Gimp, load these same images just fine; and gtk scripts that don't load icons from disk, but which draw buttons -- etc. work just fine.
How would I search for the cause of this malfunction?
Am I missing some kind of a mime-type file ?
Is there an alternate path using other gtk function calls that might accomplish the loading another way?
This works for me:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gtk
def win_with_image():
pixbuf = gtk.gdk.pixbuf_new_from_file("photo.png")
print pixbuf
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
image = gtk.Image()
image.set_from_pixbuf(pixbuf)
win.add(image)
win.connect("destroy", gtk.main_quit)
win.show_all()
if __name__ == '__main__':
win_with_image()
gtk.main()
If this doesn`t work for you, try to:
start google and type your error and choose the second link (http://aptosid.com/index.php?name=PNphpBB2&file=viewtopic&t=2246), in general this helps almost always.
reinstall libglib
install gtk (maybe some graphical libs - libpng, libjpeg, f.e.)
reinstall python/gtk package
fix broken package repository
change files permissions