[From sandbox] PIL in Python from easy to hard

[From sandbox] PIL in Python from easy to hard


To get to the complex processing algorithms, it is worthwhile to analyze the standard schemes, which is where I propose to start.

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  

Set up the tools for comfortable further work:

  image = Image.open ('test.jpg') # Open image
 draw = ImageDraw.Draw (image) # Create a drawing tool
 width = image.size [0] # Determine the width
 height = image.size [1] # Determine the height
 pix = image.load () # Uploading pixel values ​​ 

Getting Started


We will process images in RGB format. PIL also supports 1, L, P, RGB, RGBA, CMYK, YCbCr, LAB, HSV, I, F formats.

The pixel values ​​in the image are given 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 8-bit image.

Gray shade


A gray tint appears when all the color palettes are equal, 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] # find out the red color value of a pixel
  g = pix [x, y] [1] # green
  b = pix [x, y] [2] # blue
  sr = (r + g + b)//3 # mean
  draw.point ((x, y), (sr, sr, sr)) # draw a pixel

 image.save ("result.jpg", "JPEG") # do not forget to save the image
  

image
A small nuance
The human eye perceives a different spectrum of colors in different ways. No one will give you an exact formula, because the perception of colors is different for everyone anyway, but if you're interested, you can read more on here and here .


Inversion


Inversion is obtained by subtracting 255 current colors:

 
 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

Invert Gray


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 scale inversion


For this algorithm, you need to determine the threshold value, which I 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) & gt; 100: # if the sum of the values ​​is greater than 100, then use the inversion
  sr = (r + g + b)//3
  draw.point ((x, y), (255-sr, 255-sr, 255-sr))
  else: # otherwise the usual shade of gray
  sr = (r + g + b)//3
  draw.point ((x, y), (sr, sr, sr))  

image in image processing algorithms

Source text: [From sandbox] PIL in Python from easy to hard