Python Tkinter Image saying 'no such file or directory' - python-3.x

I know many questions are out there on this but none of the solutions seem to have worked.
Here is my code:
image_1 = PhotoImage(file="AeolusPavillion_01"); image_1 = subsample(2)
backImg = Label(screen, image=image_1).place(x=50,y=50)
The error I get when this is run is
_tkinter.TclError: couldn't open "AeolusPavillion_01": no such file or directory
I have tried using tk.PhotoImage() and os.path. and using the actual path directory instead of the image name too but none of these have fixed it. e.g. c:/users/...
The image file is within the same folder as the python file and I made sure it was a .png file too as I heard JPEGs don't work in tkinter.
Has anyone got any solutions to what I could try next?

Just try doing
image_1 = PhotoImage(file="AeolusPavillion_01.jpg"); image_1 = subsample(2)
backImg = Label(screen, image=image_1).place(x=50,y=50)
or whatever file type it is

Related

How do I resolve a permission error with django?

I am using Django to display my code in an html format using class based views. My code reads a log file and displays stats based on what is in there. When I try to access the log file from my computer this error message is displayed:
[Errno 13] Permission denied: 'C:/Users/bhattaar/Downloads/access.log'
I first tried going through the properties of the folder to make sure everything was set to read only (which it already was) and then I tried running the command prompt as an administrator and it still would not work.
The line the error appears on is this:
log = open('C:/Users/bhattaar/Downloads/access.log', 'r')
Does anyone know how I can resolve this issue?
Does this work?
Taken from here
log_file = r'C:/Users/bhattaar/Downloads/access.log'
with open(log_file) as f:
f = f.readlines()

I cant read the image file in the particular directory

I took some images in my camera and tried to resize them using opencv library but i think that i can't read the images I don't know the reason why.Thank you for the help in advance.
I have a python 3.8 version and the updated opencv library version.Not much of a background I guess.
import os,cv2
count=0
for file in os.listdir('E:\Projects\Python\Resixing images\Images'):
if file.endswith('.jpg'):
print(file)
img=cv2.imread(file)
img2=img.copy()
img2=cv2.resize(img2,(700,700))
name="resize"+str(count)+".jpg"
cv2.imwrite(name,img2)
count+=1
I receive an error message
P_20191107_214848_SRES.jpg
Traceback (most recent call last):
File "E:\Projects\Python\Resixing images\image changing res.py", line 7, in
img2=img.copy()
AttributeError: 'NoneType' object has no attribute 'copy'
[Finished in 9.7s]
Try this:
img=cv2.imread('E:\Projects\Python\Resixing images\Images' + '\' + file)
The problem was that you were sending only the name of the file to the python program, so the program tried to look for the image in the current directory and not at your specified path. The above change should fix the problem.
also, a good idea would be to have 2 // instead of 1 /, just to avoid any format specifier in the middle of things, or you could just use r to mention the path to be raw string
img=cv2.imread('E:\\Projects\\Python\\Resixing images\\Images' + '\\' + file)
img=cv2.imread(r'E:\Projects\Python\Resixing images\Images\' + file)

ValueError: Could not find a format to read the specified file in mode 'i'

I am trying to read a png file into a python-flask application running in docker and am getting an error that says
ValueError: Could not find a format to read the specified file in mode
'i'
i have uploaded a file using an HTML file and now i am trying to read it for further processing. i see that scipy.misc.imread is deprecated and i am trying to replace this with imageio.imread
if request.method=='POST':
file = request.files['image']
if not file:
return render_template('index.html', label="No file")
#img = misc.imread(file)
img = imageio.imread(file)
i get this error :
File "./appimclass.py", line 34, in make_prediction
img = imageio.imread(file)
File "/usr/local/lib/python3.6/site-packages/imageio/core/functions.py", line 221, in imread
reader = read(uri, format, "i", **kwargs)
File "/usr/local/lib/python3.6/site-packages/imageio/core/functions.py", line 139, in get_reader
"Could not find a format to read the specified file " "in mode %r" % mode
Different, but in case helpful. I had an identical error in a different library (skimage), and the solution was to add an extra 'plugin' parameter like so -
image = io.imread(filename,plugin='matplotlib')
Had the exact same problem recently, and the issue was a single corrupt file. Best is to use something like PIL to check for bad files.
import os
from os import listdir
from PIL import Image
dir_path = "/path/"
for filename in listdir(dir_path):
if filename.endswith('.jpg'):
try:
img = Image.open(dir_path+"\\"+filename) # open the image file
img.verify() # verify that it is, in fact an image
except (IOError, SyntaxError) as e:
print('Bad file:', filename)
#os.remove(dir_path+"\\"+filename) (Maybe)
I had this problem today, and found that if I closed the file before reading it into imageio the problem went away.
Error was:
File "/home/vinny/pvenvs/chess/lib/python3.6/site-packages/imageio/core/functions.py", line 139, in get_reader "Could not find a format to read the specified file " "in mode %r" % mode ValueError: Could not find a format to read the specified file in mode 'i'
Solution:
Put file.close() before images.append(imageio.imread(filename)), not after.
Add the option "pilmode":
imageio.imread(filename,pilmode="RGB")
It worked for me.
I encountered the same error, and at last, I found it was because the picture was damaged.
I had accidentally saved some images as PDF, so the error occurred. resolved after deleting those incompatible format images.

pyinstaller "could not parse stylesheet"

I'm building a small program using pyQt and pyInstaller.
I've tried to add an background image to my QMainWindow:
class pyPrimaMainWindow(QMainWindow):
def __init__(self):
...do some stuff...
self.setWindowIcon(QIcon(os.path.join(self.py_prima.resource_path(), "TH.ico"))) # <- this works
self.setStyleSheet("QMainWindow{{border-image: url({0});background-size:100%;}}".format(os.path.join(self.py_prima.resource_path(), "bg.png")))
The resource_path() methods looks like that:
def resource_path(self):
""" Get absolute path to resource, works for dev and for PyInstaller """
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = getattr(sys, '_MEIPASS', "C:/Users/Tobias/eclipse/workspace/PyPrima/data/")
# except Exception:
# base_path =
print(base_path)
return base_path
It's copied from the pyinstaller wiki, returns an absoulte path and works for other pictures/icons.
However, if I build an executable with pyInstaller, the programm runs nice, but the background image is missing. Instead, the console outputs
"could not parse stylesheet of object ..."
If I run the python file, it works all fine...
Any ideas on this?
Thanks!
I'll answer my own question just in case someone else stumbles upon the same problem.
The fileseparators are wrong...
Fix it with
bgpath = os.path.join(self.py_prima.resource_path(), "bg.png")
bgpath = bgpath.replace("\\", "/")
self.setStyleSheet("QMainWindow{{border-image: url({0});background-size: 100%;}}".format(
bgpath))

How to load a raster layer using PyQGIS?

Although there are some posts on this matter, there is no answer in anyone of them. This is why I am asking it again.
One post I found was https://gis.stackexchange.com/questions/68032/raster-layer-invalid
I read information from the following link: https://hub.qgis.org/wiki/17/Arcgis_rest .
I used the command: gdal_translate "http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true" s.xml -of WMS. And it generated the file successfully. However, when I try to open the file and assuming the provider is wms, the code report layer is invalid.
The code I used is:
file = QFileDialog.getOpenFileName(self,
"Open WMS", ".", "WMS (*.xml)")
fileInfo = QFileInfo(file)
# Add the layer
layer = QgsRasterLayer(file, fileInfo.fileName(),"wms")
if not layer.isValid():
print "Failed to load."
return
I just choose the file from the dialog box.
I also tried the other command: qgis.utils.iface.addRasterLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true","raster") by using the following code:
layer = QgsRasterLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer?f=json&pretty=true", "layer")
if not layer.isValid():
print "Failed to load."
return
It also report "Failed to load". The original command can be run successfully in QGIS python command line. Also, if I try to enter the code in python console, the layer.isValid() would return true. It is just not working in standalone script.
Answer can be found here: https://gis.stackexchange.com/questions/120823/how-to-load-a-wms-layer-using-pyqgis.
Basically, it is just a version problem. If you have qgis previous than v2.6, it would not work. But it is fixed for 2.6
If it is still not working for you, you most likely have problem for environment variable settings.
This is working for me for single band image.I am using python 2.7 and QGIS 2.0.1 .You can load any raster layer like wms,tiff (single band or multiband) etc. using this.:
def ifile(self):
global fileName
fileName = str(QtGui.QFileDialog.getOpenFileName(self.iface.mainWindow(),"Open Raster File",'C:\\',"raster files(*.tif *.tiff *.TIF *.TIFF *.IMG *.img )"))
if len(fileName) is 0:
return
else:
self.inFileName = fileName;
filelayer = QgsRasterLayer(fileName,os.path.basename(fileName))
if filelayer == None or filelayer.bandCount() != 1:
self.errorMessage = "Not a DEM Image"
QMessageBox.information(self.iface.mainWindow(), "Error", self.errorMessage)
else:
#f=open(str(self.inFileName))
self.dlg.lineEdit.setText(self.inFileName)
if filelayer.isValid():
QgsMapLayerRegistry.instance().addMapLayer(filelayer)
pass

Resources