Pillow Python (Watermarking) - Error Messages - python

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)

Related

SystemError: tile cannot extend outside image

I want to read a different windows tab in my computer but it seems to not accept the coordinates that i'm putting, hte coordinates i got were using pyautogui. I'm using jupyter to code it, i'm new to python so most of this code i've found in geeksforgeeks so there is somethings i still dont understand how it works, one of them is why the 'def imToString():".
import numpy as nm
import pytesseract
import cv2
import time
from PIL import ImageGrab
x = 2
time.sleep(5)
def imToString():
pytesseract.pytesseract.tesseract_cmd= r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Tesseract-OCR'
while (True):
cap = ImageGrab.grab(bbox=(220, 370, 335, 330), include_layered_windows=True)
tesstr = pytesseract.image_to_string(
cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
lang ='eng')
print(tesstr)
imToString()
---------------------------------------------------------------------------
SystemError Traceback (most recent call last)
Input In [21], in <cell line: 21>()
17 tesstr = pytesseract.image_to_string(
18 cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
19 lang ='eng')
20 print(tesstr)
---> 21 imToString()
Input In [21], in imToString()
15 while (True):
16 cap = ImageGrab.grab(bbox=(220, 370, 335, 330), include_layered_windows=True)
17 tesstr = pytesseract.image_to_string(
---> 18 cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
19 lang ='eng')
20 print(tesstr)
File C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py:675, in Image.__array__(self, dtype)
673 new["data"] = self.tobytes("raw", "L")
674 else:
--> 675 new["data"] = self.tobytes()
677 return np.array(self._ArrayData(new), dtype)
File C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py:722, in Image.tobytes(self, encoder_name, *args)
720 # unpack data
721 e = _getencoder(self.mode, encoder_name, args)
--> 722 e.setimage(self.im)
724 bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
726 data = []
SystemError: tile cannot extend outside image

storing a PILLOW image in same name after editing

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)

Why there is an attribute error while trying to display an image(PIL object)

I faced some problems while trying to save images from the archive as pillow objects to the list. I am using pillow library for python and jupyter notebook to work with the images. And initially I wanted to have a list of vocabularies, where one of the keys would be a pillow object so I could easily get my image(it seems to me so, may be I am wrong). I open images in the archive one at a time as file object and then open it as pillow object. At this step I want to save this pillow object so I could work with it later. All the images are fine, if I use display while appending them to the list, they are displayed. But there is one thing which looks weird for me. If I don't display images while they are added to the list, I can't display them further if I fetch them from that list. I wish you could help me. I suppose the problem may be in my inexperience in working with files. May be there is a better way to do what I need.
import zipfile
from PIL import Image
import pytesseract
import cv2 as cv
import numpy as np
#%%
file = zipfile.ZipFile('small_img.zip', 'r')
data = []
images = []
for name in file.namelist():
with file.open(name, 'r') as img_file:
image = Image.open(img_file)
data.append({'name': name, 'PilObject': image, 'text': None, 'bounding_boxes': None})
images.append(image)
#display(image)
#if I leave the line above I could display my images further, fetching them from the list
#If not, an error occurs
#%%
display(images[0])
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
d:\pythonprojects\untitled\venv\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
343 method = get_real_method(obj, self.print_method)
344 if method is not None:
--> 345 return method()
346 return None
347 else:
d:\pythonprojects\untitled\venv\lib\site-packages\PIL\Image.py in _repr_png_(self)
670 """
671 b = io.BytesIO()
--> 672 self.save(b, "PNG")
673 return b.getvalue()
674
d:\pythonprojects\untitled\venv\lib\site-packages\PIL\Image.py in save(self, fp, format, **params)
2122
2123 # may mutate self!
-> 2124 self._ensure_mutable()
2125
2126 save_all = params.pop("save_all", False)
d:\pythonprojects\untitled\venv\lib\site-packages\PIL\Image.py in _ensure_mutable(self)
616 def _ensure_mutable(self):
617 if self.readonly:
--> 618 self._copy()
619 else:
620 self.load()
d:\pythonprojects\untitled\venv\lib\site-packages\PIL\Image.py in _copy(self)
609
610 def _copy(self):
--> 611 self.load()
612 self.im = self.im.copy()
613 self.pyaccess = None
d:\pythonprojects\untitled\venv\lib\site-packages\PIL\ImageFile.py in load(self)
241 while True:
242 try:
--> 243 s = read(self.decodermaxblock)
244 except (IndexError, struct.error) as e:
245 # truncated png/gif
d:\pythonprojects\untitled\venv\lib\site-packages\PIL\PngImagePlugin.py in load_read(self, read_bytes)
861 self.__idat = self.__idat - read_bytes
862
--> 863 return self.fp.read(read_bytes)
864
865 def load_end(self):
~\AppData\Local\Programs\Python\Python37\lib\zipfile.py in read(self, n)
928 self._offset = 0
929 while n > 0 and not self._eof:
--> 930 data = self._read1(n)
931 if n < len(data):
932 self._readbuffer = data
~\AppData\Local\Programs\Python\Python37\lib\zipfile.py in _read1(self, n)
996 data = self._decompressor.unconsumed_tail
997 if n > len(data):
--> 998 data += self._read2(n - len(data))
999 else:
1000 data = self._read2(n)
~\AppData\Local\Programs\Python\Python37\lib\zipfile.py in _read2(self, n)
1028 n = min(n, self._compress_left)
1029
-> 1030 data = self._fileobj.read(n)
1031 self._compress_left -= len(data)
1032 if not data:
~\AppData\Local\Programs\Python\Python37\lib\zipfile.py in read(self, n)
751 "is an open writing handle on it. "
752 "Close the writing handle before trying to read.")
--> 753 self._file.seek(self._pos)
754 data = self._file.read(n)
755 self._pos = self._file.tell()
AttributeError: 'NoneType' object has no attribute 'seek'
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=3600x6300 at 0x24E8704B1C8>
So I'm curious, does the code in the question work as is?
Because there seem to be various strange things going on.
(I can't test it as is, for lack of the opencv package.)
As a baseline, used this to check that images do work,
when read from an archive.
import zipfile
from PIL import Image
archive = zipfile.ZipFile('media.zip', 'r')
fileNames = archive.namelist()
fileNames.pop(0) # Remove directory entry (here, 'media/').
# Opening the image files, could be as simple as this:
images = [Image.open(fName) for fName in fileNames]
# Test images, by displaying them with tkinter.
import tkinter as tk
from PIL import ImageTk
tk.Tk()
# Store references, to keep PhotoImages alive (for tkinter).
tkImages = [ImageTk.PhotoImage(img) for img in images]
for img in tkImages: tk.Label(image=img).pack()
tk.mainloop()
Can you update the loop where you open the images,
according to this, and see if the problem persists?

it is easy to convert a jpg to a bmp on MacOS with OpenCV. is it possible to do the job with pillow?

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

Can't get librosa load a wav file

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.

Categories

Resources