≡ Menu

playing with pillow… (part 1)

Here, we will discuss about image transformation: geometrical, color, point some image thresholding, image enhancement buy applying filters, editing GIF, drawing on an image, image conversion and modification in bulk and rolling image using PIL.
Pillow is a fork of PIL- Python Imaging Library that will support Python 3.x.

Installing pillow library:

pip install PIL

The important class of the library: Image

Opening the image and getting details about it.

from PIL import Image

im = Image.open('simpson.png')

print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG

im.show()
#To open the image

As you can see from the comand:

print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG

the image has a RGBA color profile. We can convert it to jpeg only after converting it to RGB:

rgb_im = im.convert('RGB')
rgb_im.save('simpson_new.jpg')

Rotate an image:

from PIL import Image
import os

im = Image.open('simpson.png')
im = im.rotate(45) # rotate the object im 45 degrees

rgb_im = im.convert('RGB')
rgb_im.save('simpson_45.jpg')

im.close()

You can resize the image through the resize command:

from PIL import Image
import os

im = Image.open('simpson.png')

rx = int(im.width/10)
ry = int(im.height/10)

im=im.resize((rx,ry)) #rx and ry are new pixel of image

rgb_im = im.convert('RGB')
rgb_im.save('simpson_resized.jpg')

im.close()

Add a text to immage:

from PIL import Image, ImageDraw, ImageFont
import os

im = Image.open('simpson.png')
d1 = ImageDraw.Draw(im)

myFont = ImageFont.truetype('Monofur/monofur bold Nerd Font Complete Mono Windows Compatible.ttf', 140)

d1.text((650,700), 'Hello World', font=myFont, fill=(255,255,0))

im.save('simpson_hello.png')
im.close()

Crop and paste the parts of the image:

from PIL import Image
import os

#path = # path of the image that you won't to open
#os.chdir(path)

im = Image.open('simpson.png')

print(im.size, im.mode, im.format)
#(1600, 1200) RGBA PNG



box = (531,38,957,434)  #Two points of a rectangle to be cropped
cropped_part = im.crop(box)
cropped_part = cropped_part.transpose(Image.ROTATE_180)
im.paste(cropped_part,box)


im.show()
#To open the image

{ 0 comments… add one }

Rispondi

Next post:

Previous post: