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
Related
I am trying to extract text from a gif image using the below code, it has worked for png format not working for gif.
import pytesseract
import io
import requests
from PIL import Image
url = requests.get('http://article.sapub.org/email/10.5923.j.aac.20190902.01.gif')
img = Image.open(io.BytesIO(url.content))
text = pytesseract.image_to_string(img)
print(text)
getting this error
C:\python\lib\site-packages\PIL\Image.py:1048: UserWarning: Couldn't allocate palette entry for transparency
warnings.warn("Couldn't allocate palette entry for transparency")
Traceback (most recent call last):
File "D:/elifesciences/prox.py", line 8, in <module>
text = pytesseract.image_to_string(img)
File "C:\python\lib\site-packages\pytesseract\pytesseract.py", line 345, in image_to_string
}[output_type]()
File "C:\python\lib\site-packages\pytesseract\pytesseract.py", line 344, in <lambda>
Output.STRING: lambda: run_and_get_output(*args),
File "C:\python\lib\site-packages\pytesseract\pytesseract.py", line 242, in run_and_get_output
temp_name, input_filename = save_image(image)
File "C:\python\lib\site-packages\pytesseract\pytesseract.py", line 173, in save_image
image.save(input_file_name, format=extension, **image.info)
File "C:\python\lib\site-packages\PIL\Image.py", line 2088, in save
save_handler(self, fp, filename)
File "C:\python\lib\site-packages\PIL\GifImagePlugin.py", line 507, in _save
_write_single_frame(im, fp, palette)
File "C:\python\lib\site-packages\PIL\GifImagePlugin.py", line 414, in _write_single_frame
_write_local_header(fp, im, (0, 0), flags)
File "C:\python\lib\site-packages\PIL\GifImagePlugin.py", line 532, in _write_local_header
transparency = int(transparency)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
Process finished with exit code 1
The idea is to convert each of the frames to RGB image before performing the OCR on them, as shown below -
for frame in range(0,img.n_frames):
img.seek(frame)
imgrgb = img.convert('RGBA')
imgrgb.show()
text = pytesseract.image_to_string(imgrgb)
print(text)
Working sample - https://colab.research.google.com/drive/1ctjk3hH0HUaWv0st6UpTY-oo9C9YCQdw
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.
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
This is the code(a simple python code which could add a number to a picture):
from PIL import Image, ImageDraw, ImageFont
def addnum(number, filepath):
img = Image.open(filepath)
width, height = img.size
draw = ImageDraw.Draw(img)
front_size = height/4
ttf_front = ImageFont.truetype('Arial.ttf', front_size)
draw.text((width - front_size, 0), number, (255, 0, 0), font = ttf_front)
del draw
img.save('wechat_addnum.jpg')
img.show()
if __name__ == '__main__':
addnum('4','wechat.jpg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/Users/JourneyWoo/Python/python100/python001/python000.py", line 27, in <module>
addnum('4','wechat.jpg')
File "/Users/JourneyWoo/Python/python100/python001/python000.py", line 16, in addnum
draw = ImageDraw.Draw(img)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageDraw.py", line 299, in Draw
return ImageDraw(im, mode)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageDraw.py", line 60, in __init__
im.load()
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageFile.py", line 244, in load
raise_ioerror(err_code)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageFile.py", line 59, in raise_ioerror
raise IOError(message + " when reading image file")
IOError: broken data stream when reading image file
I don't know the real problem, and from the google and other questions from stackoverflow I cannot find the method which could solve this problem.
Thank you!!
This is a know issue. Try to update Pillow using pip install Pillow --upgrade
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