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())
Related
I am hoping to classify some line drawings with a pretrained resnet model and am loading them from a github page. I think the error is coming from me setting up the location of the file wrong, but any help would be appreciated.
The link for the github is here
Here is my code:
loc = 'https://github.com/AlexSwiderski/Images/tree/main/pnt'
fname1 = 'ambulance_resized.png'
response = requests.get(loc + fname1)
image = Image.open(BytesIO(response.content)).resize((256, 256))
data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.
My error is as follows:
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-29-6e447d67525f> in <module>()
4 fname1 = 'ambulance_resized.png'
5 response = requests.get(loc + fname1)
----> 6 image = Image.open(BytesIO(response.content)).resize((256, 256))
7 data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.
8
/usr/local/lib/python3.7/dist-packages/PIL/Image.py in open(fp, mode)
2894 warnings.warn(message)
2895 raise UnidentifiedImageError(
-> 2896 "cannot identify image file %r" % (filename if filename else fp)
2897 )
2898
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f61e16decb0>
You need add a slash before the string, otherwise the concatenated path would be
"https://github.com/AlexSwiderski/Images/tree/main/pntambulance_resized.png"
Which is invalid.
loc = 'https://github.com/AlexSwiderski/Images/tree/main/pnt'
fname1 = '/ambulance_resized.png'
response = requests.get(loc + fname1)
image = Image.open(BytesIO(response.content)).resize((256, 256))
data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.
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)
I want to save my plotly in svg format, but I get an error and cannot save it.
I could have converted it to html by using plotly.offline.plot(fig, filename= 'aaa.html'), but it didn't work.
fig = px.line(
df_list[i],
x=x_axis,
y=y_axis,
color="species",
color_discrete_sequence=colors
)
fig.write_image("SVG/aa.svg")
error message
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-2f45787db90f> in <module>
27 )
28 # plotly.offline.plot(fig, filename= 'aaa.html')
---> 29 fig.write_image("SVG/aa.svg")
30 # plotly.offline.plot(fig, filename= 'aaaa.svg')
c:\users\owner\appdata\local\programs\python\python38-32\lib\site-packages\plotly\basedatatypes.py in write_image(self, *args, **kwargs)
3249 import plotly.io as pio
3250
-> 3251 return pio.write_image(self, *args, **kwargs)
3252
3253 # Static helpers
c:\users\owner\appdata\local\programs\python\python38-32\lib\site-packages\plotly\io\_kaleido.py in write_image(fig, file, format, scale, width, height, validate, engine)
242 # -------------
243 # Do this first so we don't create a file if image conversion fails
--> 244 img_data = to_image(
245 fig,
246 format=format,
c:\users\owner\appdata\local\programs\python\python38-32\lib\site-packages\plotly\io\_kaleido.py in to_image(fig, format, width, height, scale, validate, engine)
100 from ._orca import to_image as to_image_orca
101
--> 102 return to_image_orca(
103 fig,
104 format=format,
c:\users\owner\appdata\local\programs\python\python38-32\lib\site-packages\plotly\io\_orca.py in to_image(fig, format, width, height, scale, validate)
1533 # Make sure orca sever is running
1534 # -------------------------------
-> 1535 ensure_server()
1536
1537 # Handle defaults
c:\users\owner\appdata\local\programs\python\python38-32\lib\site-packages\plotly\io\_orca.py in ensure_server()
1388 # Validate orca executable only if server_url is not provided
1389 if status.state == "unvalidated":
-> 1390 validate_executable()
1391 # Acquire lock to make sure that we keep the properties of orca_state
1392 # consistent across threads
c:\users\owner\appdata\local\programs\python\python38-32\lib\site-packages\plotly\io\_orca.py in validate_executable()
1074
1075 if executable is None:
-> 1076 raise ValueError(
1077 """
1078 The orca executable is required to export figures as static images,
ValueError:
The orca executable is required to export figures as static images,
but it could not be found on the system path.
Searched for executable 'orca' on the following path:
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)
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