ValueError: Could not find a format to read the specified file in mode 'i' - python-3.x

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.

Related

FastText Error! ValueError: (file-name) cannot be opened for training

I Have installed fasttext module in Python and loaded the model [ 'cc.en.300.bin'].
I already made the data frame format according to the fasttext. and then generating the files
train.to_csv(" ecomm.train",columns=['Category_description'], index= False, header= False)
test.to_csv("ecom.test", columns=['Category_description'], index= False, header= False)
the files created successfully! then when I run this code
import fasttext
mod= fasttext.train_supervised(input='ecomm.train')
I get this error:
Traceback (most recent call last):
File "/Users/rosie/Documents/ProGraMinG/Python/pythonProject/FastText/FastText_overview.py", line 97, in <module>
mod= fasttext.train_supervised(input='ecomm.train')
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/fasttext/FastText.py", line 533, in train_supervised
fasttext.train(ft.f, a)
ValueError: ecomm.train cannot be opened for training!
{ UPDATE } !!!
Used both isfile() and exists() functions to check if the file exists:
path = 'Users/rosie/Documents/ProGraMinG/Python/pythonProject/FastText/ecomm.train'
check_file = os.path.isfile(path)
print("isfile method ",check_file)
check_file = os.path.exists(path)
print("exists method ",check_file)
Both methods returns ' False '.
I also checked if the file is readable or not
doc= open(' ecomm.train', 'r')
print('checking if the file is readable', doc.readable())
However, it returned 'True', now I'm confused. As for the size of the ' ecomm.train', it is 29.4 MB
Are you sure the file is readable, at the simple (local) path 'ecomm.train', from your Python process, given its current local orking directory?
For example, try specifying the file as its full absolute path – on MacOS probably something like /Users/yourusername/yourdirectory/etc/etc/ecomm.train. If that works, the problem was that your Python code's effective directory wasn't what you expected.
Alternatively, if the process that wrote the file was in some way a different user than the later process trying to read it, there might be permission errors.
Totally separate from fasttext, you could check, from the same code that's about to try fasttext operations, if the file is readable (via either the local path, or the absolute path) using a recipe lie that in this other answer: https://stackoverflow.com/a/44213239/130288
Even if it fails, it might give a more-explanatory error.

Python Tkinter Image saying 'no such file or directory'

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

FileNotFoundError: [WinError 2] The system cannot find the file specified while loading model from s3

I have recently saved a model into s3 using joblib
model_doc is the model object
import subprocess
import joblib
save_d2v_to_s3_current_doc2vec_model(model_doc,"doc2vec_model")
def save_d2v_to_s3_current_doc2vec_model(model,fname):
model_name = fname
joblib.dump(model,model_name)
s3_base_path = 's3://sd-flikku/datalake/current_doc2vec_model'
path = s3_base_path+'/'+model_name
command = "aws s3 cp {} {}".format(model_name,path).split()
print('saving...'+model_name)
subprocess.call(command)
It was successful, but after that when i try to load the model back from s3 it gives me an error
model = load_d2v("doc2vec_model")
def load_d2v(fname):
model_name = fname
s3_base_path='s3://sd-flikku/datalake/current_doc2vec_model'
path = s3_base_path+'/'+model_name
command = "aws s3 cp {} {}".format(path,model_name).split()
print('loading...'+model_name)
subprocess.call(command)
model=joblib.load(model_name)
return model
This is the error i get:
loading...doc2vec_model
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in load_d2v
File "C:\Users\prane\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 339, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Users\prane\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 800, in __init__
restore_signals, start_new_session)
File "C:\Users\prane\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 1207, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I don't even understand why it is saying File not found, this was the path i used to save the model but now i'm unable to get the model back from s3. Please help me!!
I suggest that rather than your generic print() lines, showing your intent, you should print the actual command you've composed, to verify that it makes sense upon observation.
If it does, then also try that exact same aws ... command directly, at the command prompt where you had been launching your python code, to make sure it runs that way. If it doesn't, you may get a more clear error.
Note that the error you're getting doesn't particularly look like it's coming from the aws command, of from the S3 service - which might talk about 'paths' or 'objects'. Rather, it's from the Python subprocess system & Popen' call. I think those are via your call tosubprocess.call(), but for some reason your line-of-code isn't shown. (How are you running the block of code with theload_d2v()`?)
That suggests the file that's no found might be the aws command itself. Are you sure it's installed & runnable from the exact working-directory/environment that your Python is running in, and invoking via subprocess.call()?
(BTW, if my previous answer got you over your sklearn.externals.joblib problem, it'd be good for you to mark the answer as accepted, to save other potential answerers from thinking that's still an unsolved question that's blocking you.)
try to add extension of your model file to your fname if you are confident the model file is there.
e.g. doc2vec_model.h3

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)

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