width, height = resized_image.size
dummyImg = np.zeros([height, width, 4], dtype=np.uint8)
for x in range(width):
for y in range(height):
color = seg_map[y,x]
(r,g,b) = resized_image.getpixel((x,y))
if color == 0:
dummyImg[y,x] = [255,255,255,255]
else:
dummyImg[y,x] = [r,g,b,255]
img = Image.fromarray(dummyImg)
outputFilePath = '15d09a689ca0d4 Mod.jpg'
img.save(outputFilePath)
Hello, I am getting this error while trying to save image as "JPG", I included alpha channels in dummyimg.
Traceback (most recent call last):
File "/home/timmy/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 620, in _save
rawmode = RAWMODE[im.mode]
KeyError: 'RGBA'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/timmy/Desktop/image-background-removal-master/impr.py", line 79, in <module>
img.save(outputFilePath)
File "/home/timmy/.local/lib/python3.6/site-packages/PIL/Image.py", line 2007, in save
save_handler(self, fp, filename)
File "/home/timmy/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 622, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode RGBA as JPEG
I checked GitHub issue cannot write mode RGBA as JPEG (4.2.0) , they said it is solved and is now doable
JPEG file format cannot handle transparency. To save an image with color and transparency you need to use another format (e.g. PNG).
You can save to JPEG only if you drop the alpha channel and make all pixels opaque.
Related
i draw a text to a image and i set the fill and i get an error , but i do not for the fill it get nothing for my image
from PIL import Image, ImageDraw
img = Image.open('test.png')
d = ImageDraw.Draw(img)
d.text((100, 100), "HELLO", fill="red")
img.save('testssss.png')
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImagePalette.py", line 99, in getcolor
return self.colors[color]
KeyError: (255, 0, 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 20, in <module>
d.text((100, 100), "HELLO", fill="red")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 455, in text
ink = getink(fill)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 403, in getink
ink, fill = self._getink(fill)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 111, in _getink
ink = self.palette.getcolor(ink)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImagePalette.py", line 109, in getcolor
self.palette[index + 256] = color[1]
IndexError: bytearray index out of range
The image:
my system : replit(linux)
Try, (255,0,0) instead of red.
from PIL import Image, ImageDraw
img = Image.open('test.png')
d = ImageDraw.Draw(img)
d.text((100, 100), "HELLO", fill=(255,0,0))
img.save('testssss.png')
You should also look at the size of your image, it might be too small for the text you are using. You can try reducing from (100,100) to maybe (10,10) first and see if it works.
It could also be a case where you don’t have enough bits for the colour because your image is less than 256 bits per colour palette. You can also try converting your image to an rgb image using the following command before you add the text. Do
img = img.convert("RGB")
I have written a function to load images (jpg, JPEG, png, gif etc.) and convert it to jpg. The code looks like this:
def jpg_image_open(file_path, fill_color=(255, 255, 255)):
image = PIL.Image.open(file_path)
print(file_path, image.mode)
if file_path.endswith('.gif'):
# print(image.is_animated, image.n_frames)
for im_frame in PIL.ImageSequence.Iterator(image):
# Converting it to RGB to ensure that it has 3 dimensions as requested
im_frame = im_frame.convert('RGB')
image = im_frame
break
elif file_path.endswith('.png'):
image.load()
if image.mode in ('P', 'L'):
image.convert("RGB")
elif image.mode in ('RGBA', 'LA'):
# https://stackoverflow.com/a/9459208/2049763
print(file_path, " has transparency layer")
# image.load() # required for png.split()
background = PIL.Image.new(image.mode[:-1], image.size, fill_color)
background.paste(image, image.split()[-1])
image = background
return image, np.array(image)
I usually call it from other files without error.
# read input image as numpy array
loaded_img, in_image = create_my_tf_record_util.jpg_image_open(img_file)
PIL.Image.fromarray(in_image, 'RGB').save(out_img_file)
It works great for all images except, if the image is in mode 'P', 'L'.
Traceback (most recent call last):
File "dataset_tools/create_my_tf_record_coco.py", line 322, in thread_cube_map_annotation_png
PIL.Image.fromarray(in_image, 'RGB').save(out_img_file)
File "/home/mazhar/miniconda3/envs/mytfenv/lib/python3.6/site-packages/PIL/Image.py", line 2554, in fromarray
return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
File "/home/mazhar/miniconda3/envs/mytfenv/lib/python3.6/site-packages/PIL/Image.py", line 2497, in frombuffer
return frombytes(mode, size, data, decoder_name, args)
File "/home/mazhar/miniconda3/envs/mytfenv/lib/python3.6/site-packages/PIL/Image.py", line 2430, in frombytes
im.frombytes(data, decoder_name, args)
File "/home/mazhar/miniconda3/envs/mytfenv/lib/python3.6/site-packages/PIL/Image.py", line 812, in frombytes
raise ValueError("not enough image data")
ValueError: not enough image data
I am doing a small script to paste an image into a black background to have same size images for a dataset. Here is the script:
for file in glob.glob(imagetteDir):
r = str(file)
image = Image.open(file)
img = np.zeros([100,100,3],dtype=np.uint8)
imageio.imwrite('black.tif', img)
black = Image.open('black.tif')
position = ((black.width - image.width), (black.height - image.height))
print(position)
Image.Image.paste(black,image,position)
dirr , name = r.split("imagette")
path1 = name.raplace("Hexagone_resized","Hexagone")
print(path1)
black.save(imagetteresizeDir+path1)
So Image.Image.paste() make the following error that i didnt find how to resolve:
Traceback (most recent call last):
File "C:\Users\user\Documents\Project\segmentation\Imagette creation\resizing.py", line 29, in <module>
Image.Image.paste(black,image)
File "C:\Users\user\Anaconda3\envs\tf_gpu\lib\site-packages\PIL\Image.py", line 1455, in paste
im.load()
File "C:\Users\user\Anaconda3\envs\tf_gpu\lib\site-packages\PIL\TiffImagePlugin.py", line 1070, in load
return self._load_libtiff()
File "C:\Users\user\Anaconda3\envs\tf_gpu\lib\site-packages\PIL\TiffImagePlugin.py", line 1182, in _load_libtiff
raise OSError(err)
OSError: -2
Have you any idea from where it might come?
Thanks in advance for your help
i amusing PIL to write some text inside and an image and then saving it at the same location. Following is my function which does this
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
def add_text_to_image(image_path):
img = Image.open(image_path)
img = img.convert('RGB')
widht, height = img.size
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("helvetica.ttf", 20)
draw.text((0, 0), "Some text", (0, 0, 0), font=font)
img.save(image_path)
But i am getting following error.
Traceback (most recent call last): File
"/usr/local/lib/python3.6/site-packages/background_task/tasks.py",
line 43, in bg_runner func(*args, **kwargs) File
"/home/paksign/app/app/document/tasks.py", line 74, in
document_status_changed_to_completed
add_branding_texts_to_document_images(meta) File
"/home/paksign/app/app/document/utils.py", line 277, in
add_branding_texts_to_document_images for snapshot in snapshots: File
"/home/paksign/app/app/document/utils.py", line 270, in
add_text_to_image img.save(image_path) File
"/usr/local/lib/python3.6/site-packages/PIL/Image.py", line 1994, in
save save_handler(self, fp, filename) File
"/usr/local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line
761, in _save ImageFile._save(im, fp, [("jpeg", (0, 0)+im.size, 0,
rawmode)], bufsize) File
"/usr/local/lib/python3.6/site-packages/PIL/ImageFile.py", line 519,
in _save s = e.encode_to_file(fh, bufsize) OSError: [Errno 9] Bad file
descriptor Marking task
document.tasks.document_status_changed_to_completed as failed
i have tried some solution from internet but nothing is working and i don't know what i am doing wrong here. any help is appreciated
I followed this tutorial and the guy used the one of the 2 images as the mask. But for me it's not working. Why is this?
from PIL import Image
img1 = Image.open("beach.jpg")
img2 = Image.open("joker.jpg")
maxsize = min(img1.size,img2.size)
newratio = min(maxsize[0]/img2.size[0],maxsize[1]/img1.size[1])
newimg1width = int(img1.size[0]*newratio)
newimg1height = int(img1.size[1]*newratio)
newimgtuple = (newimg1width,newimg1height)
newimg = img1.resize(newimgtuple)
compimg = Image.composite(newimg, img2, newimg)
compimg.save("compimg.jpg")
The error:
Traceback (most recent call last):
File "C:\Users\dude\Desktop\Desktop\Projects\Youtube\Wordtoon\test.py", line 44, in <module>
compimg = Image.composite(newimg, img2, newimg)
File "C:\Users\dude\AppData\Local\Programs\Python\Python35-32\lib\site-packages\PIL\Image.py", line 2376, in composite
image.paste(image1, None, mask)
File "C:\Users\dude\AppData\Local\Programs\Python\Python35-32\lib\site-packages\PIL\Image.py", line 1344, in paste
self.im.paste(im, box, mask.im)
ValueError: bad transparency mask