📜 ⬆️ ⬇️

Python PIL from easy to hard

To get to the complex processing algorithms, it is worth analyzing the standard schemes, which is where I suggest starting.

For processing examples, an image with different color sets will be used:

image
')
To start, we need two library modules:

from PIL import Image, ImageDraw 

We will set up tools for comfortable further work:

 image = Image.open('test.jpg') #   draw = ImageDraw.Draw(image) #     width = image.size[0] #   height = image.size[1] #   pix = image.load() #    

Let's get started


PIL works with RGB images.

Pixel values ​​in the image are specified in the format: (x, y), (red, green, blue) , where x, y are the coordinates, and the numeric RGB values ​​are in the range from 0 to 255. That is, we work with an 8-bit image.

Shade of gray


A gray tint appears in the case of equality of all color palettes, so we need to get the arithmetic average value in all three points:

 for x in range(width): for y in range(height): r = pix[x, y][0] #     g = pix[x, y][1] # b = pix[x, y][2] # sr = (r + g + b) // 3 #  draw.point((x, y), (sr, sr, sr)) #  image.save("result.jpg", "JPEG") #    

image

Inversion


Inversion is obtained by subtracting the current color from 255:

 for x in range(width): for y in range(height): r = pix[x, y][0] g = pix[x, y][1] b = pix[x, y][2] draw.point((x, y), (255 - r, 255 - g, 255 - b)) 

image

Grayscale Inversion


Combining the two previous algorithms, you can write the following code:

 for x in range(width): for y in range(height): r = pix[x, y][0] g = pix[x, y][1] b = pix[x, y][2] sr = (r + g + b) // 3 draw.point((x, y), (255 - sr, 255 - sr, 255 - sr)) 

image

Selective gray inversion


For this algorithm, you need to determine the threshold value, which I will take for 100:

 for x in range(width): for y in range(height): r = pix[x, y][0] g = pix[x, y][1] b = pix[x, y][2] if (r+g+b)>100: #    100 ,    sr = (r + g + b) // 3 draw.point((x, y), (255-sr, 255-sr, 255-sr)) else: #    sr = (r + g + b) // 3 draw.point((x, y), (sr, sr, sr)) 

image

Conclusion


In the following articles, I would like to talk about how to approach image filtering more locally, by dividing it into areas, and also to show the interesting features of DFS in image processing algorithms.

Source: https://habr.com/ru/post/451074/


All Articles