Adding a text to an image in Python - python

Is there the most popular way of adding a text on an image in Python? I found a few completely different approaches, this seems to be best, but it doesn't work:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
img = Image.open("/full_path/1.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 16)
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
img.save('/full_path/sample-out.jpg')
After its running, the picture still doesn't have a text on it.

try this:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
img=Image.open("pathToImage")
font = ImageFont.truetype("pathToFont",10)
draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(255,255,0),font=font)
draw = ImageDraw.Draw(img)
draw = ImageDraw.Draw(img)
img.save("a_test.png")

Related

im trying to read the data from the image using pytesseract

i tried to open read the image using the pytesseract , however the code is not able to read it please check this photo im using for reading the text.
below is my code:-
import cv2
import time
import pyscreenshot as ImageGrab
import pytesseract
pytesseract.pytesseract.tesseract_cmd=r'C:/Users/RTam/AppData/Local/Programs/Tesseract-OCR/tesseract.exe'
def takescreenshot():
path= (r'C:\Users\RTam\Desktop\python basics\web scraping\Pyautogui\photos')
im=ImageGrab.grab(bbox=(900,1000,1200,1100))
im.save(path+'\\'+'ss.png')
img= cv2.imread(r'C:\Users\RTam\Desktop\python basics\web scraping\Pyautogui\photos\ss3.png')
cv2.imshow('sample',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
sample_text= pytesseract.image_to_string(img)
print(sample_text)
the only output im getting is and empty space please help
Eventually, I found the answer to my question.
However this code will not run properly in Spyder IDE, so we should make sure we have the latest tesseract version.
import cv2
import time
import pyscreenshot as ImageGrab
import pytesseract
pytesseract.pytesseract.tesseract_cmd=r'C:/Users/RTam/AppData/Local/Programs/Tesseract-OCR/tesseract.exe'
def takescreenshot():
path= (r'C:\Users\RTam\Desktop\python basics\web scraping\Pyautogui\photos')
im=ImageGrab.grab(bbox=(900,1000,1200,1100))
im.save(path+'\\'+'ss.png')
img= cv2.imread(r'C:\Users\RTam\Desktop\python basics\web scraping\Pyautogui\photos\ss3.png')
def clerify_pic():
img2 = cv2.resize(img, (0, 0), fx=2, fy=2)
gry = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
thr = cv2.threshold(gry, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
return pytesseract.image_to_string(thr)

how can I type persian text in pillow library

How can I write Persian text on photos with the help of Pillow Library in Python?
When I try to write text, the letters of the word are written from the end to the beginning.
For example, when I want to write "Hello World" in Persian, it becomes "dolW olleH" on the photo.
pillow persian writing problem:
from PIL import Image, ImageDraw, ImageFont
a = Image.open('1.jpg')
draw = ImageDraw.Draw(a)
font = ImageFont.truetype('Dana.ttf', size=200)
draw.text((100, 200), 'سلام دنیا', font=font, fill=(255, 255, 255))
See this. It'll help you to write in Arabic/Persian in Pillow.
# Tested on Python 3.6.1
# install: pip install --upgrade arabic-reshaper
import arabic_reshaper
# install: pip install python-bidi
from bidi.algorithm import get_display
# install: pip install Pillow
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
# use a good font!
fontFile = "/Users/amirreza/pil/Sahel.ttf"
# this was a 400x400 jpg file
imageFile = "/Users/amirreza/pil/input.jpg"
# load the font and image
font = ImageFont.truetype(fontFile, 18)
image = Image.open(imageFile)
# first you must prepare your text (you dont need this step for english text)
text = "سلام ایران"
reshaped_text = arabic_reshaper.reshape(text) # correct its shape
bidi_text = get_display(reshaped_text) # correct its direction
# start drawing on image
draw = ImageDraw.Draw(image)
draw.text((0, 0), bidi_text, (255,255,255), font=font)
draw = ImageDraw.Draw(image)
# save it
image.save("output.png")

How to put text on multiple images using python?

from PIL import Image, ImageDraw, ImageFont
import glob
import os
images = glob.glob("directory_path/*.jpg")
for img in images:
images = Image.open(img)
draw = ImageDraw.Draw(images)
font = ImageFont.load_default() #Downloaded Font from Google font
text = "Text on all images from directory"
draw.text((0,150),text,(250,250,250),font=font)
images.save(img)
I have to put text on all images , I have tried above code but its not working
This code worked for me just fine, but the text was hard to read because it was small and white. I did change directory_path to images and put my images in there. The images looked like this, the text is small and on the left side:
Here is the solution
from PIL import Image,ImageDraw,ImageFont
import glob
import os
images=glob.glob("path/*.jpg")
for img in images:
images=Image.open(img)
draw=ImageDraw.Draw(images)
font=ImageFont.load_default()
text="Whatever text"
draw.text((0,240),text,(250,250,250),font=font)
images.save(img)
one possible problem with the code may be that you are using the images variable for saving the list of images and also to iterate through the images.
Try this code, this will work for sure.
from PIL import Image, ImageDraw, ImageFont
import glob
import os
images = glob.glob("new_dir/*.jpg")
print(images)
for img in images:
image = Image.open(img)
draw = ImageDraw.Draw(image)
font = ImageFont.load_default() #Downloaded Font from Google font
text = "Text on all images from directory"
draw.text((0,150),text,fill = 'red' ,font=font)
image.save(img)

PIL: OSError: Unknown File Format

Attempted to use a piece of code from other questions on Stack Overflow. Ran into this piece of code:
from PIL import ImageFont
from urllib.request import urlopen
truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf'
font = ImageFont.truetype(urlopen(truetype_url), size=10)
I got this error:
OSError: unknown file format
I tried other suggestions such as reinstalling PIL, using requests.get and I receive the same error. I checked the link and it does take you to the item in question. Are there other suggestions I can try?
My Goal:
Be able to take a font from a link so I do not have to do this locally on my computer.
Thanks!
You can do it like this:
from PIL import Image, ImageFont, ImageDraw
import requests
import io
# Load font from URI
truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf?raw=true'
r = requests.get(truetype_url, allow_redirects=True)
font = ImageFont.truetype(io.BytesIO(r.content), size=24)
# Create a black canvas and get drawing context
canvas = Image.new('RGB', (300,180))
draw = ImageDraw.Draw(canvas)
# Write in our font
draw.text((10, 10), "Got that crazy font", font=font, fill=(255,255,255))
canvas.save('result.png')
As Karl points out in the comments, you can do it with urllib as you were originally intending like this:
from urllib.request import urlopen
truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf?raw=true'
font = ImageFont.truetype(urlopen(truetype_url), size=10)

Where are images saved when creating images with Pillow in Python

In these lines of code, I create a small red image and save it as "new_image.png". But I can't find the saved image, where is it saved? And can I change the place where I want to save my image?
from PIL import Image
img = Image.new('RGB', (60, 30), color = 'red')
img.save("new_image.PNG")
I tested your code:
from PIL import Image
img = Image.new('RGB', (60, 30), color = 'red')
img.save("new_image.PNG")
It works well for me:
The reason may because your current work path is not as you thought.
See my answer here:
https://stackoverflow.com/a/66449241/12838403
If you don't specify a path, the image is saved in the same path as the python file generating the image
from PIL import Image
img = Image.new('RGB', (60, 30), color = 'red')
img.save("new_image.PNG")
To save image in a directory you specify, you can use
from PIL import Image
import os
image_path = "path/to/image"
image = image.save(f"{image_path}/image.png")
Note: If this directory does not exist, you would have to create it before saving your image in it.
from PIL import Image
import os
image_path = "path/to/image"
os.mkdir(image_path)
image = image.save(f"{image_path}/image.png")

Categories