I want to crop a set of Pillow images and save it with the same name in the same folder, from where it is opened. It is clustered and stored into 4 groups.
I wrote the code as below.
for c in range(4):
for image_file in glob.glob(f"plot_images/{c}/*.jpg"):
im=Image.open(image_file)
im = im.convert("RGB")
im = im.crop(offset)
im.save(im.filename)
It gives me the error
AttributeError Traceback (most recent call last)
<ipython-input-24-9f3d3a38e4e4> in <module>
15 im = im.crop(offset)
16 #im.show()
---> 17 im.save(im.filename)
18 #print(c,end='\r')
19
/srv/conda/envs/notebook/lib/python3.8/site-packages/PIL/Image.py in __getattr__(self, name)
539 )
540 return self._category
--> 541 raise AttributeError(name)
542
543 #property
AttributeError: filename
I don't understand why the error comes. please help.
If you check type(im) in different moments then you should see PIL.JpegImagePlugin.JpegImageFile after loading but PIL.Image.Image after converting which don't have filename. Use image_file instead of im.filename
im.save(image_file)
im = Image.open(image_file)
print(type(im)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
im = im.convert("RGB")
print(type(im)) # <class 'PIL.Image.Image'>
im = im.crop(offset)
print(type(im)) # <class 'PIL.Image.Image'>
im.save(image_file)
Related
Im trying to read my dataset file through 'IMAGE_PATH' but it seems its not working. 'med/s' is my dataset file. Im using google colab as IDE.
IMAGE_PATH = 'meds/'
reader = easyocr.Reader(['en'], gpu=False)
result = reader.readtext(IMAGE_PATH)
result
```
i get this error
ValueError
Traceback (most recent call last)
<ipython-input-12-7400931fefc3> in <module>()
1 reader = easyocr.Reader(['en'], gpu=False)
----> 2 result = reader.readtext(IMAGE_PATH)
3 result
7 frames
/usr/local/lib/python3.7/dist-packages/imageio/core/functions.py in get_reader(uri, format, mode, **kwargs)
137 if format is None:
138 raise ValueError(
--> 139 "Could not find a format to read the specified file " "in mode %r" % mode
140 )
141
ValueError: Could not find a format to read the specified file in mode 'i'
so I am trying to pick a folder, select every photo, watermark it with an individual text and safe it in a different folder.
I have watched a lot of YouTube Videos and googled a lot but I can't help it anymore... Im always getting error messages and I can't see why.
So my current code is:
import PIL
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import os
for f in os.listdir('.'):
if f.endswith('.jpg'):
i = Image.open(f)
draw = ImageDraw.Draw(f)
text = "Test, 22.01.2021"
font = ImageFont.truetype("arial.ttf",75)
textwidth, textheight = draw.textsize(text, font)
width, height = f.size
x=width/2-textwidth/2
y=height-textheight-300
draw.text((x,y), text, font=font)
fn, fext = os.path.splitext(f)
i.save('Test/{}.jpg'.format(fn))
Errors:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageDraw.py in Draw(im, mode)
464 try:
--> 465 return im.getdraw(mode)
466 except AttributeError:
AttributeError: 'str' object has no attribute 'getdraw'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
<ipython-input-5-5c49936ed159> in <module>
9 if f.endswith('.jpg'):
10 i = Image.open(f)
---> 11 draw = ImageDraw.Draw(f)
12 text = "Jonas Knaab, 22.01.2021"
13 font = ImageFont.truetype("arial.ttf",75)
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageDraw.py in Draw(im, mode)
465 return im.getdraw(mode)
466 except AttributeError:
--> 467 return ImageDraw(im, mode)
468
469
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageDraw.py in __init__(self, im, mode)
57 defaults to the mode of the image.
58 """
---> 59 im.load()
60 if im.readonly:
61 im._copy() # make it writeable
AttributeError: 'str' object has no attribute 'load'
------------------
Maybe you guys can help me somehow?
Cheers
!!EDIT!!
after changing ..."Draw(f)" to "Draw(i) I do not get the same error messages but it still doesn't work.
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-9-3b2bbb3d5783> in <module>
11 draw = ImageDraw.Draw(i)
12 text = "Jonas Knaab, 22.01.2021"
---> 13 font = ImageFont.truetype("arial.ttf",75)
14 textwidth, textheight = draw.textsize(text, font)
15 width, height = f.size
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageFont.py in truetype(font, size, index, encoding, layout_engine)
640
641 try:
--> 642 return freetype(font)
643 except OSError:
644 if not isPath(font):
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageFont.py in freetype(font)
637
638 def freetype(font):
--> 639 return FreeTypeFont(font, size, index, encoding, layout_engine)
640
641 try:
/opt/anaconda3/lib/python3.7/site-packages/PIL/ImageFont.py in __init__(self, font, size, index, encoding, layout_engine)
186 return
187 self.font = core.getfont(
--> 188 font, size, index, encoding, layout_engine=layout_engine
189 )
190 else:
OSError: cannot open resource
You're using string as an argument to ImageDraw.Draw(). Use i variable instead of f.
i = Image.open(f)
draw = ImageDraw.Draw(i)
Using colab (python), to visualize a unconfirmed planetary object; this happens! I don't get it! Please help... here is my code
https://colab.research.google.com/github/spacetelescope/notebooks/blob/master/notebooks/MAST/TESS/interm_tesscut_dss_overlay/tesscut_dss_overlay.ipynb#scrollTo=hNBL87NF9Wml&uniqifier=1
CODE with issues:
#display the gif
if not os.path.exists(gif):
print("No gif found. Cannot display gif of time-series.")
Image(gif, embed=True)
ERROR log:
ValueError Traceback (most recent call last) <ipython-input-27-d599e0c825fd> in <module>()
2 print("No gif found. Cannot display gif of time-series.")
3
----> 4 Image(gif, embed=True)
/usr/local/lib/python3.6/dist-packages/IPython/core/display.py in
__init__(self, data, url, filename, format, embed, width, height, retina, unconfined, metadata) 1013 1014 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
-> 1015 raise ValueError("Cannot embed the '%s' image format" % (self.format)) 1016 self.width = width 1017 self.height = height
ValueError: Cannot embed the 'gif' image format
Instead of embedding the filepath:
Image(gif, embed=True)
you can embed the image bytes directly:
Image(open(gif, 'rb').read())
it is very easy to convert a jpg to a bmp on MacOS with OpenCV.
import cv2
img = cv2.imread('a.jpg',1)
cv2.imwrite('a.bmp',img)
I am curious if it possible to do the job with pillow?
here is the piece of code on this post
from PIL import Image
import numpy as numpy
img = Image.open("xhty23.jpg").convert('L')
im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))
visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())
result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')
the file saved by above looks like
which is far from a bmp format of original image.
saving image as bmp encounters error.
-------------------------------------------------------------------------- KeyError Traceback (most recent call
last) in ()
3 b = np.abs(np.fft.rfft2(a))
4 j = Image.fromarray(b)
----> 5 j.save("a",".bmp")
~/anaconda3/envs/tf11/lib/python3.6/site-packages/PIL/Image.py in
save(self, fp, format, **params) 1956 save_handler =
SAVE_ALL[format.upper()] 1957 else:
-> 1958 save_handler = SAVE[format.upper()] 1959 1960 if open_fp:
KeyError: '.BMP'
j.save("a.bmp")
gets this error
-------------------------------------------------------------------------- KeyError Traceback (most recent call
last)
~/anaconda3/envs/tf11/lib/python3.6/site-packages/PIL/BmpImagePlugin.py
in _save(im, fp, filename)
272 try:
--> 273 rawmode, bits, colors = SAVE[im.mode]
274 except KeyError:
KeyError: 'F'
During handling of the above exception, another exception occurred:
OSError Traceback (most recent call
last) in ()
3 b = np.abs(np.fft.rfft2(a))
4 j = Image.fromarray(b)
----> 5 j.save("a.bmp")
~/anaconda3/envs/tf11/lib/python3.6/site-packages/PIL/Image.py in
save(self, fp, format, **params) 1967 1968 try:
-> 1969 save_handler(self, fp, filename) 1970 finally: 1971 # do what we can to clean up
~/anaconda3/envs/tf11/lib/python3.6/site-packages/PIL/BmpImagePlugin.py
in _save(im, fp, filename)
273 rawmode, bits, colors = SAVE[im.mode]
274 except KeyError:
--> 275 raise IOError("cannot write mode %s as BMP" % im.mode)
276
277 info = im.encoderinfo
OSError: cannot write mode F as BMP
I already tried everything in this post, none of them works.
any ideas?
You can do that more simply with SIPS - Apple's built-in "Scriptable Image Processing System" which has shipped with all versions of macOS/OSX since the year dot. No need to install any Python or PIL/Pillow packages.
Just in Terminal:
sips -s format bmp input.jpg --out output.bmp
I got an audio dataset of many wav files and tired to use librosa to edit, but I have trouble reading some certain files by using librosa.load.Could someone help me figure it out?
here is my code:
import librosa
sound_clip = librosa.load('audio/fold1/180937-7-3-10.wav')
print(sound_clip)
here is the error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-93fe2f032e98> in <module>()
----> 1 sound_clip = librosa.load('audio/fold1/180937-7-3-10.wav')
2 print(sound_clip)
/home/uri7910/anaconda2/envs/tensorflow011/lib/python2.7/site-packages/librosa/core/audio.pyc in load(path, sr, mono, offset, duration, dtype)
107
108 y = []
--> 109 with audioread.audio_open(os.path.realpath(path)) as input_file:
110 sr_native = input_file.samplerate
111 n_channels = input_file.channels
/home/uri7910/anaconda2/envs/tensorflow011/lib/python2.7/site-packages/audioread/__init__.pyc in audio_open(path)
100 from . import maddec
101 try:
--> 102 return maddec.MadAudioFile(path)
103 except DecodeError:
104 pass
/home/uri7910/anaconda2/envs/tensorflow011/lib/python2.7/site-packages/audioread/maddec.pyc in __init__(self, filename)
24 def __init__(self, filename):
25 self.fp = open(filename, 'rb')
---> 26 self.mf = mad.MadFile(self.fp)
27 if not self.mf.total_time(): # Indicates a failed open.
28 raise UnsupportedError()
AttributeError: 'module' object has no attribute 'MadFile'
The failing line is:
self.mf = mad.MadFile(self.fp)
AttributeError: 'module' object has no attribute 'MadFile'
This looks to be a problem with the pyMad library. Would suggest looking into upgrading or reinstalling. that library. If that fails you might want to raise a bug.