Python. PIL library

12.6.2.1 determine standard colors by RGB code
12.6.2.3 apply graphic primitives to create drawings. 

12.6.2.2 use commands of module Image in PIL library (load, create, size, save) to manipulate images; 

PIL library

The PIL (Python image library), or rather its Pillow modification, is used to work with images.

To install the library, you need to run the pip install <Module name> command:

Win + R --> cmd -->

c:\.....>pip install pillow

Image creation and drawing

Using the PIL library, you can create new images. The Image.new function takes an RGB palette type, a tuple with the size of the new image, and a color to fill the image with.
The following example creates a 300 x 300 pixels im image object filled with red:

from PIL import Image
im = Image.new("RGB", (300, 300), (255, 0, 0))
print(im.size)   # image size (300, 300)
im.save("red_square.jpg")

In order for the system to understand where to create the object, you need to save the *.py file. The image will be created in the same directory (folder).

After executing the program folder, we get the following image:

To draw graphic primitives, Draw objects from the PIL.ImageDraw module. This object has many tools for creating graphic primitives: lines, ellipses, points, rectangles, arcs, etc.

color = (R, G, B) # R, G, B - integers from 0 to 255

Draw line:

draw.line((x0, y0, x1, y1), fill=color, width=n) 

Draw a green line from bottom-left to top-right with a width of 3 pixels:

from PIL import Image, ImageDraw
new_image = Image.new("RGB", (200, 300), (0, 0, 0)) # create image
draw = ImageDraw.Draw(new_image)                    # on image create picture for drawing
draw.line((0, 300, 200, 0), fill=(0, 255, 0), width=3) # draw line 
new_image.save('green_line.png', "PNG")             # save image to PNG format

Draw an ellipse

draw.ellipse((x0, y0, x1, y1), fill=color, width=n) 

Draw a rectangle

draw.rectangle((x0, y0, x1, y1), fill=color, outline=color) # outline is a border of rectangle

Draw polygon

draw.polygon(((x0, y0), (x1, y1), (x2, y2), (x3, y3), (x4, y4)), color)


Questions:

1. Name the library for working with the Draw module.

2. Explain what the RGB color model means.

3. List the graphical functions of the module Draw and describe the arguments of each.


Exercises:

 


Tasks:

Tasks on Stepik.org course "Python Programming for NIS"

Категория: Programming languages | Добавил: bzfar77 (08.09.2022)
Просмотров: 7712 | Теги: Python, size, Load, PIL, Save, create, Draw | Рейтинг: 4.7/11
Всего комментариев: 0
avatar