I have a folder that contains 2000 TIF images and I want to convert them to jpg images.
I wrote two codes and both work well until they convert 370 images and then they raise an error
Here is my first code :
DestPath='/media/jack/Elements/ToJPG95/'
from PIL import Image
import os
def change(path, row):
filename1=path+row
filename=row.split('.')[0] + '.jpg'
im = Image.open(filename1)
img= im.convert('RGB')
Dest=os.path.join(DestPath,filename)
img.save(Dest, format='JPEG',quality=95)
import csv
sourcePath='/media/jack/Elements/TifImages/'
with open("TIFFnames.csv") as f:
filtered = (line.replace('\n', '') for line in f)
reader = csv.reader(filtered)
for row in filtered:
change(sourcePath , row)
and here is my second code which I ran in inside the folder that has the images :
from PIL import Image # Python Image Library - Image Processing
import glob
DestPath='/media/jack/Elements/ToJPG95/'
print(glob.glob("*.TIF"))
for file in glob.glob("*.TIF"):
im = Image.open(file)
rgb_im = im.convert('RGB')
rgb_im.save(DestPath+file.replace("TIF", "jpg"), quality=95)
# based on SO Answer: https://stackoverflow.com/a/43258974/5086335
they convert up to 370 images and then give an error
Here is the error I am getting :
Traceback (most recent call last):
File "conmg.py", line 7, in <module>
rgb_im = im.convert('RGB')
File "/home/jack/.local/lib/python3.6/site-packages/PIL/Image.py", line 873, in convert
self.load()
File "/home/jack/.local/lib/python3.6/site-packages/PIL/TiffImagePlugin.py", line 1070, in load
return self._load_libtiff()
File "/home/jack/.local/lib/python3.6/site-packages/PIL/TiffImagePlugin.py", line 1182, in _load_libtiff
raise OSError(err)
OSError: -2
I have tried imagemagick mentioned in the solution Here
but this is what I am getting when I click enter to run the command:
jack#jack-dell:/media/jack/Elements/TifImages$ for f in *.tif; do echo "Converting $f"; convert "$f" "$(basename "$f" .tif).jpg"
>
>
>
>
As you can see, it does nothing
I think the codes work well but for some reason they fail after converting 370 images
I am running on a 6 TB external hard drive.
Can any one tell me please whats wrong ?
As #fmw42 says, you likely have a problem with the 370th file (corrupt, or some ill-supported TIFF variant). You bash code will convert all the files that can be read, it doesn't work because you are missing a closing done:
for f in *.tif; do echo "Converting $f"; convert "$f" "$(basename "$f" .tif).jpg" ; done
Your Python would also convert all the readable files if you use try/except to catch errors and continue with the next file:
for file in glob.glob("*.TIF"):
try:
im = Image.open(file)
rgb_im = im.convert('RGB')
rgb_im.save(DestPath+file.replace("TIF", "jpg"), quality=95)
except:
print('File not converted:',file)
Related
This is my code
from PIL import Image
from PIL import ImageDraw
# Open an Image
FRAME_SIZE = (720,1280)
img = Image.new('RGB', FRAME_SIZE, color = 'black')
# Call draw Method to add 2D graphics in an image
I1 = ImageDraw.Draw(img)
# Add Text to an image
I1.text((100, 100), "nice Car", fill=(255, 32, 0))
# Display edited image
img.show()
# Save the edited image
img.save("./new_folder/car2.png")
And this is error.
Traceback (most recent call last):
File "D:\Python Projects\devops-directive-hello-world\trial.py", line 19, in <module>
img.save("./new_folder/car2.png")
File "C:\Users\Pushpendra\Desktop\Drone\devops-directive-hello-world\lib\site-packages\PIL\Image.py", line 2317, in save
fp = builtins.open(filename, "w+b")
FileNotFoundError: [Errno 2] No such file or directory: './new_folder/car2.png'
Process finished with exit code 1
Just change the destination folder.
img.save("car2.png")
this will do the trick. At least you must choose an existing directory
The most possible reason for this error to occur is your Python directory is in C: so your relative path is referencing your Python directory only.
Work around in this case can be to use absolute path, like so : 'D/Python Projects/newfolder/'
Hopefully it solves your problem
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.
I am trying to access to the temperature data stored in a tiff-file. I was provided with a python script that was supposed to be able to do this, but I keep getting the following error:
Traceback (most recent call last):
File "read_tiff.py", line 57, in <module>
im = Image.open(sourcePath)
File "/Users/myname/opt/anaconda3/lib/python3.8/site-packages/PIL/Image.py", line 2943, in open
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file 'Testbild.tiff'
This is the relevant section of the code:
sourcePath = "Testbild.tiff"
im = []
try:
sourcePath = sys.argv[1]
except IndexError:
print('usage: python read_tiff.py filename')
sys.exit()
try:
im = Image.open(sourcePath)
except FileNotFoundError:
print('File not found: ' + sourcePath)
sys.exit()
imarray = np.array(im)
This is what I checked:
with another random tiff file it worked, so it is probably not the script but the file itself (/maybe I need to install some additional package??)
the tiff file can be opened without a problem in IrfanView and Photoscan
when prompting "file Testbild.tiff" I get "Testbild.tiff: TIFF image data, little-endian" so it definitely IS a tiff file
Is anyone able to help me out?
Cheers!
EDIT:
The import statement for Image is from PIL import Image
If necessary, these are all the import statements of the script:
import matplotlib.pyplot as plt
from PIL import Image
import sys
import numpy as np
import math
import cv2
Try using:
from skimage import io
im = io.imread(sourcePath)
This will open it directly as an array as well.
In my case, it worked to read .tif file to ndarray:
path2dir = r'C:\data\WORK\image4example'
name_img = 'Slice_25.tif'
path2img = os.path.join(path2dir, name_img)
im = cv2.imread(path2img , cv2.IMREAD_ANYDEPTH)
plt.imshow(im)
from os import listdir
import cv2
files=listdir('/home/raymond/Desktop/Test/Test') #Importing the dir for cropping
for file in files:
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
crop_img = img[0:1600, 0:1600]
cv2.imwrite('/home/raymond/Desktop/Test/cropped'+file,crop_img) # write new data to img
Im trying to loop crop images, while getting an error of
Traceback (most recent call last):
File "Files.py", line 8, in <module>
crop_img = img[0:1600, 0:1600]
TypeError: 'NoneType' object is not subscriptable
(fixi) ➜ exercises
You are probably missing a slash at the end of the path here:
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
Should be:
img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file) # reading a single image from the dir
or even better:
import os
img = cv2.imread(os.path.join('/home/raymond/Desktop/Test/Test/',file)) # reading a single image from the dir
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file)
Hello Dan Raymond,
This cannot work because Python does not add a slash (/) before listed filenames.
Which means that if you have a filename "hello", then what is appended to '/home/raymond/Desktop/Test/Test' is "hello" which results in '/home/raymond/Desktop/Test/Testhello' which does not exist.
Replace your line with this:
img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file)
I just have started with Python and Numpy arrays. I am reading a huge amount of image data set located in many different folders. Although, everything is working fine when reading the images, but I continuously getting an error which I am not sure about what really is it. I tried to research for it, but unfortunately I failed to get the real answer. Please help me regarding this issue.
My code is below.
import os
import numpy as np
import matplotlib.pyplot as mpplot
import matplotlib.image as mpimg
images = []
path = "../compCarsThesisData/"
for root, _, files in os.walk(path):
current_directory_path = os.path.abspath(root)
for f in files:
name, ext = os.path.splitext(f)
if ext == ".jpg":
current_image_path = os.path.join(current_directory_path, f)
current_image = mpimg.imread(current_image_path)
images.append(current_image)
print(files)
for img in images:
print (img.shape)
The error I'm facing is below also.
File "reading.py", line 15, in <module>
current_image = mpimg.imread(current_image_path)
File "C:\Users\zeele\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\image.py", line 1359, in imread with Image.open(fname) as image:
File "C:\Users\zeele\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2618, in open
prefix = fp.read(16)
OSError: [Errno 22] Invalid argument
P.S. As a new member please don't mind if the question is unclear or not direct. Your help will be highly appreciated.
Thanks.