Python. PIL library. Image processing.

12.6.2.2 use commands of module Image in PIL library (load, create, size, save) to manipulate images.
12.6.2.4 create filters for image processing.

PIL library. Image processing.

from PIL import Image

im = Image.open("sea.PNG") # upload picture from *.py directory
im.save("sea2.PNG") # save picture to *.py directory
Model example

Consider an example of working with an image in which we:

  1. Let's go through each pixel in the image.
  2. Get the color value for it in RGB notation.
  3. Assign a new color value to this pixel (change the components).
  4. In the end, save the resulting image with a new name.

How to get color from pictures?

Load pixels and Change color

from PIL import Image
im = Image.open("sea.PNG")
pixels = im.load()  # list with pixels
x, y = im.size  # width (x) and height (y) of pictures
for i in range(x):  
    for j in range(y):
        r, g, b = pixels[i, j] # take RGB values of pixel [i, j] 
        pixels[i, j] = g, b, r # put RGB values of pixel [i, j]
im.save("sea2.PNG")
Get three colors from pixel

You can use:
r, g, b = pixels[i, j]or:
pixel = pixels[i, j]
r = pixel[0]
g = pixel[1]
b = pixel[2]
ImageFilter module in PIL

from PIL import Image, ImageFilter

im = Image.open("sea.PNG")
im1 = im.filter(ImageFilter.BLUR)
im1.show() # or save(filename)
Types of filters in ImageFilter

  • BLUR
  • CONTOUR
  • DETAIL
  • EDGE_ENHANCE
  • EDGE_ENHANCE_MORE
  • EMBOSS
  • FIND_EDGES
  • SHARPEN
  • SMOOTH
  • SMOOTH_MORE

Questions:


Exercises:


Tasks:

 

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

Task "Source picture"

Open an image file and get a copy of the image into a new file.

Task "Red channel"

Edit picture. Get only the red channel of the picture. The green and blue channels of all pixels replace to 0.

Task "Black and white image"

Convert any pictures to the black-white picture.

Each color = (R + G + B) / 3

 

Категория: Algorithms | Добавил: bzfar77 (22.09.2022)
Просмотров: 5539 | Теги: Image, Python, PIL | Рейтинг: 5.0/2
Всего комментариев: 0
avatar