PIL for Python image processing


Preface

PIL (Python Imaging Library) is a Python image processing library. At present, the development of the PIL project has been stopped. The last update was in 2011.
Emphasis: PIL does not support Python 3.x

Pillow is also an image processing library for Python, which is different from PIL: Pillow is a specific version of PIL Fork code, Pillow is compatible with most uses of PIL, and is actively developed. More importantly, Pillow library supports Python 3.x, so Pillow is recommended.

  • installation

pip install pillow

Insert picture description here

Basic image processing: PIL
advanced image processing: Opencv


1. Pillow use

1.1 Image creation test

Pillow can also create a new blank image. The first parameter is mode, which is the color space mode, the second parameter specifies the resolution (width x height) of the image, and the third parameter is color.

  • You can directly fill in the names of commonly used colors. Such as'red'
  • You can also fill in the color represented by hexadecimal, such as #FF00O for red.
  • You can also pass in tuples, such as (255, 0, 0, 255) or (255, 0, 0) for red.

1.2 Color and RGBA

RGB: Red Green Blue Alpha (transparency)
computer usually express the image as RGB value, or add alpha value (transparency, transparency), calledRGBA value. In Pillow, the value of RGBA is represented as a tuple consisting of 4 integers, R, G, IB, and A respectively. The range of integer is 0~255. All 0s in RGB can represent black, and all 255s represent black. It can be guessed that
(255, 0, 0, 255) represents red, because the R component is the largest, and the G and B components are 0, so it appears red.
But when the alpha value is 0, no matter what the color is, the color is invisible and can be understood as transparent .
Insert picture description here
Insert picture description here
Insert picture description here

Second, use steps

2.1 Image reading test

The code is as follows (example):

frim PIL import Image

image = Image.open("dog.png")
print(img.format)
print(img.mode)
print(img.size)
img.show() #show方法显示图片
  • Output

PNG
RGB
(600,375)

A picture consists of three colors, RGB (Red, Green, and Blue), and Newton's ternary colors. The **split()** function can decompose a picture into three pictures according to the color, a picture of a single color Display, the default is grayscale display image

r,g,b = img.spilt()
#单通道显示图像
b.show()

Insert picture description here
The three colors that were originally split are shuffled and recombined. The color of the picture has changed, and the original green picture has become a red picture.

# 打乱顺序,重新合并
img = Image.merge("RGB",(g,b,r))
img.show()

Insert picture description here

2.2 Crop image

Image has a crop() method that receives a rectangular area tuple (the order is ( left , top , right , bottom ). It returns a new Image object, which is the cropped image, and has no effect on the original image. The
code is as follows (example) :

cropimg = img.crop((100,100,400,400)) 
cropimg.show() 

Insert picture description here

2.3 Copy and Paste

Image's copy function will produce a copy of the original image as its name suggests, and any operations on this copy will not affect the original image. The paste() method is used to paste (overlay) an image on top of another image. Whoever calls it will directly modify the Image object.
Insert picture description here
If the information of the original image will be used later, it will be very troublesome because the information is changed. Therefore, it is best to use copy() to copy a copy before paste. The copy operation will not affect the original image information. Although the original image information has been changed in the program, the other file names used when saving the file are equivalent to the change not taking effect, so the original image remains unchanged when viewed.

2.4 Taking ID photos for dogs

With the width and height of the cropped image as the interval, they are continuously pasted in the copy in the loop, which is a bit like taking an ID photo.

The code is as follows (example):

# 截取狗狗图片区域
cropimg = img.crop((200,120,300,220))

crop_width, crop_height = cropimg.size
width,height = img.size

copyimg = img.copy() # 副本 copyimg = img
for left in range(0,width,crop_width):
	for top in range(0,height,crop_height):
		copyimg.past(cropimg,(left,top)) # 粘贴到copyimg
		
copyimg.show()

Insert picture description here

2.5 Resize the image

resizeThe method returns a new Image object with the specified width and height, and accepts a tuple containing the width and height as a parameter. The value of width and height is an integer.
Set the width and height to be the same, it becomes a square image, and the image is stretched

The code is as follows (example):

width,height = img.size
resizeimg = img.resize((width,width))
resizeimg.show()

Insert picture description here

2.6 Rotate and flip the image

rotateReturn the rotated new Image object, keeping the original image unchanged. Anticlockwise rotation.
save can directly save the picture

The code is as follows (example):

img.rotate(90).save("rotate90.png")
img.rotate(270).save("rotate270.png")
img.rotate(20).save("rotate20.png")
img.rotate(180).save("rotate180.png")
  • Mirror flip of image
img.transport(Image.FLIP_LEFT_RIGHT).show()
img.transport(Image.FLIP_TOP_BOTTOM).show()

2.7 Image filtering

Pillow useImageFilterCommon operations such as image blur, edge enhancement, sharpness, and smoothing can be easily done.

The code is as follows (example):

from PIL import ImageFilte

# 高斯模糊
image.filte(ImageFilter.GaussianBlur).show()
# 普通模糊
image.filte(ImageFilter.BlUR).show()
# 边缘增强
image.filte(ImageFilter.EDGE_ENHANCE).show()
# 找到边缘
image.filte(ImageFilter.FIND_EDGES).show()
# 浮雕
image.filte(ImageFilter.EMBOSS).show()
# 轮廓
image.filte(ImageFilter.CONTOUR).show()
# 锐化
image.filte(ImageFilter.SHARPER).show()
# 平滑
image.filte(ImageFilter.SMOOTH).show()
# 细节
image.filte(ImageFilter.DETAIL).show()

2.8 ImageDraw module

The ImageDraw module provides the Draw class, which can perform simple 2D drawing on Image instances

  • Draw class painting function
  • chord
  • arc
  • pieslice fan-shaped
  • ellipse draw ellipse
  • line draw line/polyline
  • point点
  • polygon draw polygon
  • rectangle draw rectangle
  • text text

Three, Chinese verification code

3.1 Random color background image

  • Reference library

from PIL import Image,ImageDraw
import random

The code is as follows (example):

from PIL import Image,ImageDraw
import random

# 生成一张背景图,随机颜色

# 定义一个函数生成随机颜色
def randcolor():
    return (random.randint(0,255),random.randint(0,255),random.randint(0,255))

size = width,height = 240,60
img = Image.new('RGB',size,randcolor())#随机生成颜色

# 每个像素填充随机色
draw = ImageDraw.Draw(img) # 画笔
for x in range(width):
    for y in range(height):
        draw.point((x,y),fill=randcolor())

img.show()

Insert picture description here

3.2 Random font

The code is as follows (example):

# 定义随机字库
chars = "百度新闻是包含海量资讯的新闻服务平台,真实反映每时每刻的新闻热点"

def randChar():
    return chars[random.randint(0,len(chars)-1)]

3.3 Blur processing

The code is as follows (example):

......
font = ImageFont.truetype(r'C:\Windows\Fonts\SIMYOU.TTF',36,)
......

# 写字 (width/4 * i + 10 ,10)这是位置不断运行 不断调整
for i in range(4):
    draw.text((width/4 * i + 10 ,10),randChar(),font=font,fill=randcolor1())

# 普通模糊处理
img = img.filter(ImageFilter.BLUR)
  • Windows font library

Insert picture description here

  • operation result
    Insert picture description here

Source code

Guess you like

Origin blog.csdn.net/HG0724/article/details/113186934