I am new to Python and tried to run the following code. I received the following error "IOError: cannot open resource". Is this due to the fact that some of the Image characteristics do not longer exist (e.g. Coval.otf), or is it potentially due to writing/reading restrictions? please let me know - many thanks, W
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from skimage import transform as tf
def create_captcha(text, shear=0, size=(100,24)):
im = Image.new("L", size, "black")
draw = ImageDraw.Draw(im)
font = ImageFont.truetype(r"Coval.otf", 22)
draw.text((2, 2), text, fill=1, font=font)
image = np.array(im)
affine_tf = tf.AffineTransform(shear=shear)
image = tf.warp(image, affine_tf)
return image / image.max()
%matplotlib inline
from matplotlib import pyplot as plt
image = create_captcha("GENE", shear=0.5)
It's because Coval.otf cannot be read, probably because it doesn't exist on your system, this is specified in the ImageFont doc. I tried searching for the specific font and found no way of aquiring it. Look at #NewYork167's link if you must use the Coval font.
Either way, to save yourself the trouble of installing fonts, you could just change the call to a font that exists on your system, use the one specified in the example of the docs:
font = ImageFont.truetype("arial.ttf", 15)
For me after running the following:
conda install -c conda-forge graphviz
conda install -c conda-forge python-graphviz
and then linking the font on mac by:
img = Image.open("tree1.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15)
It worked perfectly.
If you are using colab then you will have to provide path properly just writing arial.ttf is not sufficient.
To get the path if that font-type is available on colab :
!fc-list or !fc-list | grep ""
and then you can add the whole path.enter image description here
Looks like you can install Coval from here to save you from having to change fonts in future code as well
https://fontlibrary.org/en/font/bretan
The font files for PIL on windows are case sensitive.
Go to Windows/fonts:
Some fonts are *.tff
Others are *.TFF
You have to use the actual file name and not the font title thingy that Windows shows from control panel.
I also found that for Anaconda3 2019.03 the truetype font var is case sensitive. I'm using Windows 10, and had to look in C:\Windows\Fonts. Looking at the properties I saw the 'Arial.ttf' font was 'arial.ttf' in the explorer.
ImageFont.truetype('arial.ttf') works while
ImageFont.truetype('Arial.ttf') throws a 'cannot open resource' error.
Annoying change, but worked for me.
In my case (Centos, Python 3.6.6), the font requires absolute path like:
ttfont = ImageFont.truetype('/root/pyscripts/arial.ttf',35)
The relative path like ~/pyscripts/arial.ttf won't work.
Related
This question already has answers here:
How to draw arabic text on the image using `cv2.putText`correctly? (Python+OpenCV)
(2 answers)
Closed 8 months ago.
I used to see many programs that can render arabic text with no bugs just fine, but when it comes to python there is only one lib that i know of (arabic_reshaper) and it's not efficient yet as it contains bugs, so i wonder if there any way around like an api or some twisted efficient way to do this task?
Yes.
You'll have to use arabic_reshaper & python-bidi and a proper font. After trying many fonts I found only 2 fonts working: "Pak Nastaleeq.ttf" & "AA Sameer Qamri Regular.ttf" You can download the .ttf file of any of these fonts & use that.
Here's a n example code in python depicting how to do this:
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import arabic_reshaper
from bidi.algorithm import get_display
text = "چوكسے ہنجاریں الجمل تیج اکساہٹ"
reshaped_p = arabic_reshaper.reshape(text)
text = get_display(reshaped_p)
cat_image = Image.open("test_image.png")
drawing_on_img = ImageDraw.Draw(cat_image)
font = ImageFont.truetype('Pak Nastaleeq.ttf',size=15)
text_color = (201,50,250)
text_coordinates = (0,0)
drawing_on_img.text(text_coordinates,text,font=font,fill='black')
cat_image.save("text_on_test_imager.png")
You can use Pillow without arabic_reshaper.
First of all you need have libraqm on your path. The Raqm library encapsulates the logic for complex text layouts and provides a convenient API. libraqm relies on the following libraries: FreeType, HarfBuzz, FriBiDi, make sure that you install them before installing libraqm if not available as package in your system.
if you using macos you can install libraqm with homebrew
brew install libraqm
Pillow wheels since version 8.2.0 include a modified version of libraqm that loads libfribidi at runtime if it is installed.
The .text function takes the direction argument to the
libraqm library, which enables pillow to support bidirectional text (using FriBiDi), shaping (using HarfBuzz), and also proper script itemization.
Additionally, you need a font for the language you wish to write in, such
as an Arabic font.
import os
from PIL import Image, ImageDraw, ImageFont
def main():
image = Image.open(os.path.join(os.path.dirname(__file__), "nature.jpeg"))
font = ImageFont.truetype(
os.path.join(
os.path.dirname(__file__), "vazir-font-v28.0.0", "Vazir-Regular.ttf"
),
100,
)
text = "طبیعت زیبای دوست داشتنی"
canvas = ImageDraw.Draw(image)
canvas.text((0, 0), text, (255, 255, 255), font=font, direction="rtl")
image.save(os.path.join(os.path.dirname(__file__), "result.jpg"))
if __name__ == '__main__':
main()
I'm trying to read a jpg file using Pillow (Version 3.2.0) in Jupyter notebook (Python 3.4), but it fails with the following error:
OSError: broken data stream when reading image file
I'm using the following code:
from PIL import Image
im = Image.open("/path/to/image.jpeg")
im.show()
It works fine both in the interactive Python shell and using Python 2.7 instead of 3.4.
I've followed these steps already: Using Pillow with Python 3
Anyone an idea what's going on?
Looks like you're not pointing to the directory where your photo is stored.
import os
defaultWd = os.getcwd()
defaultWd # Sets your curretn wd
os.chdir(defaultWd + '\\Desktop') # Points to your photo--e.g., on Desktop
os.getcwd() # Shows change in wd
from PIL import Image
im = Image.open("Mew.jpg")
im.show() # Will plot to your default image viewing software
And another way if you don't want to change current wd:
im = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
im.show()
And if you want to plot inline:
from matplotlib.pyplot import imshow
%matplotlib inline
inlinePic = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
imshow(inlinePic)
Note: You may also want to simply try typing 'jpg' instead of 'jpeg' as you did above, if your image is in your current working directory. Also, if PIC is not installed, you'll get this error NameError: name 'Image' is not defined.
The problem was related to another import: I was importing Tensorflow before PIL, which caused the problem. Same issue as this one: https://github.com/scikit-image/scikit-image/issues/2000. Changing the order of the imports solved it.
I have an issue with writing text to an image under Python and PIL -
I'm able to write text to a png file, though not bold text. Could anyone provide an example of how to achieve this?
I thought the easiest solution may be was use a bold-variant of a text, but I'm unable to see anything in the Windows/font folder that supplies this - does this mean font types have a 'bold attribute' that is T/F?:
Code I'm using:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
# font = ImageFont.truetype("Arial-Bold.ttf",14)
font = ImageFont.truetype("Arial.ttf",14)
img=Image.new("RGBA", (500,250),(255,255,255))
draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(0,0,0),font=font)
draw = ImageDraw.Draw(img)
img.save("a_test.png")
A simple way to do it:
font = ImageFont.load_default().font
Also you can do a google search for 'verdana.ttf' and download it put it in the same directory as the python file:
Then add it like this:
font = ImageFont.truetype("Verdana.ttf",14)
You aren't looking at actual font files in the control panel (explorer magically turns into the font viewer control panel when in the Windows/fonts folder as well), they are grouped by family for your convenience. Double click the family to see the fonts in the family:
Then right-click and choose properties to find the file name:
Here's the code I'm using:
from PIL import Image
import ImageFont, ImageDraw
import sys
import pdb
img = Image.new("RGBA",(300,300))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(sys.argv[1],30)
draw.text((0,100),"world",font=font,fill="red")
del draw
img.save(sys.argv[2],"PNG")
and here's the image that results:
img http://www.freeimagehosting.net/image.php?976a0d3eaa.png ( for some reason, I can't make it show on SO, so the link is http://www.freeimagehosting.net/image.php?976a0d3eaa.png )
The thing is, I don't understand why it isn't drawing the font correctly? I should be able to read the word "world" off of it. It's like the picture's been cut in half or something. Does anyone have any clue?
EDIT: after balpha's comment, I decided to try another font. I'm only interested in ttf fonts, so I tried with another one, and it worked. This is kind of strange. The original font I tried to run this with is Beautiful ES. I'm curious if you guys can reproduce the same image on your computers, and if you happen to know the reason for why that is.
PIL uses the freetype2 library, so most possibly it is an issue with the font file; for example, it could have bad metrics defined (e.g see the OS/2 related ones opening the font with FontForge).
This is an issue I already asked about and several got answers but the problem remained.
when I try to write in hebrew to an image using Image module I get instead of the hebrew lettring some other (ascii??) lettering. if I convert to unicode or ascii I get an error that it doesn't support. I got here a reference to a code that does what I want in chinese:
import sys
import Imag
import ImageDraw
import ImageFont
import _imaging
txt = '你好,世界!'
font = ImageFont.truetype('c:/test/simsun.ttc',24)
im = Image.new("RGBA",(300,200),(0,0,0))
draw = ImageDraw.Draw(im)
#draw.text( (0,50), u'你好,世界!', font=font)
draw.text( (0,50), unicode(txt,'UTF-8'), font=font)
but then I get an error:ImportError:
The _imagingft C module is not installed.
the same goes when I try to use standrad hebrew font 'arial.ttf' (with hebrew string ofcourse). as you can see I have imported _imaging succsefuly so the problem doesn't lay there as suggested by effbot.org.
it seem that the problem is with the Imagefont.truetype(...).
any help will be very appriciated
Sounds like PIL was built without FreeType support. Install the FreeType dev files and rebuild PIL again.
the problem was the PIL 1.1.7 doesn't work well with windows XP. the same code runs well under linux or with XP but with PIL 1.1.6
mystory is solved