1. Install pillow
pip install pillow
2. Introduction to image processing
Image processing RGB color mode:
-R(red) 0--255
-G(green) 0--255
-B(blue) 0--255
Pixel array
Each point is a pixel. Each point is represented by (R, G, B) color
Picture material:
3. Module introduction
A.Image model
(1) Open the picture
Example: Open a picture with Image
#导入模块
from PIL import Image
#打开图片
img=Image.open('kiki.jpg')
#显示图片
img.show()
print('图片格式:',img.format)
print('图片大小:',img.size)
print('高度:',img.height)
print('宽度:',img.width)
print('(100,100)处的RGB:',img.getpixel((100,100)))
'''
图片格式 JPEG
图片大小 (500, 330)
高度 330
宽度 500
(100,100)处的RGB (2, 6, 5)
'''
(2) Mixed
①Transparency blending
blend(im1,im2,alpha)
im1: picture 1, im2: picture 2, alpha blending transparency (0-1) is the proportion of im2
Note: the size of im1 and im2 need to be the same
Specific mixing formula: im1*(1-alpha)+im2*alpha
#导入模块
from PIL import Image
#打开图片
img1=Image.open('kiki.jpg')
img2=Image.open('yoki.jpg')
#图片混合
img1add2=Image.blend(img1,img2,0.5)
#显示图片
img1add2.show()
Mixed results
②Mask blend
composite(im1,im2,mask)
Function: Use mask to process im1 and im2 together. The three pictures of im1, im2 and mask are required to have the same size.
#导入模块
from PIL import Image
#打开图片并变成相同尺寸(这里本来就相同)
img1=Image.open('kiki.jpg')
img2=Image.open('yoki.jpg').resize(img1.size)
img3=Image.open('niki.jpg').resize(img1.size)
#把img3的rgb分离
r3,g3,b3=img3.split()
img1composite2=Image.composite(img1,img2,b3)
#显示图片
img1composite2.show()
result:
(3) Image zoom
① Pixel zoom (in fact, brightness adjustment):
#导入模块
from PIL import Image
#打开图片
img1=Image.open('kiki.jpg')
#将每个像素值扩大2倍
img1_mul2=Image.eval(img1,lambda x:x*2)
#显示图片
img1_mul2.show()
result:
②Size scaling (change size):
#导入模块
from PIL import Image
#打开图片
img1=Image.open('kiki.jpg')
img2=img1.copy()
#将每个像素值缩小一半
img2.thumbnail((img1.size[0]/2,img1.size[1]/2))
#显示图片大小
print('img1:',img1.size)
print('img2:',img2.size)
'''
img1: (500, 330)
img2: (250, 165)
'''
(4) Paste and cut
①Paste:
Image.paste(im,box=None,mask=None)
im: source image or pixel value; box: paste area; mask: mask
box:
a. (x1, y1): align the upper left corner of the image (x1, y1), and discard beyond the pasted image area
b. (x1, y1, x2, y2): The original image is consistent with this area.
c. None: The original image and the pasted image must have the same size.
#导入模块
from PIL import Image
#打开图片
img1=Image.open('kiki.jpg')
img2=img1.copy()
#将每个像素值缩小一半
img2.thumbnail((img1.size[0]/3,img1.size[1]/3))
#把img2贴到img1上
img1.paste(img2,(30,40))
img1.show()
result:
(5) Image rotation
Image.rotate(angle,resample=0,expand=0,center=None,translate=None,fillcolor=None)
angle: rotation angle
#导入模块
from PIL import Image
#打开图片
img1=Image.open('kiki.jpg')
img1=img1.rotate(60)
img1.show()
(6) Format conversion
#导入模块
from PIL import Image
#打开图片
img1=Image.open('kiki.jpg')
#上下滤镜
#img2=img1.transpose(Image.FLIP_TOP_BOTTOM)#上下
img2=img1.transpose(Image.FLIP_LEFT_RIGHT)#左右
img2=img1.transpose(Image.ROTATE_90)#旋转90度,尺寸也变
img2=img1.transpose(Image.ROTATE_180)#旋转180度
img2.show()
(7) Image separation (split), mixing (merge)
#导入模块
from PIL import Image
#打开图片
img1=Image.open('kiki.jpg')
img2=Image.open('yoki.jpg').resize(img1.size)
#分离
r1,g1,b1=img1.split()
r2,g2,b2=img2.split()
tempa=[r1,g2,b1]
tempb=[r2,g1,b2]
#混合
imga=Image.merge('RGB',tempa)
imgb=Image.merge('RGB',tempb)
imga.show()
imgb.show()
(7) Image filter
BLUR : Blur filtering
CONTOUR : Contour filter
DETAIL : Detail filtering
EDGE_ENHANCE : boundary enhancement filtering
EDGE_ENHANCE_MORE : boundary enhancement filtering (deeper)
EMBOSS : Relief filter
FIND_EDGES : Find boundary filtering
SMOOTH : smoothing filter
SMOOTH_MORE : smoothing filter (deeper)
SHARPEN : sharpening filter
GaussianBlur(radius=2) : Gaussian Blur
Example:
#导入模块
from PIL import Image,ImageFilter
#打开图片
img1=Image.open('kiki.jpg')
img1.thumbnail((img1.size[0]/3,img1.size[1]/3))
w,h=img1.size
#输出图片
img_output=Image.new('RGB',(3*w,4*h))
#高斯模糊
img1_GaussianBlur=img1.filter(ImageFilter.GaussianBlur(radius=3))
#BLUR普通模糊
img1_BLUR=img1.filter(ImageFilter.BLUR)
#DETAIL细节滤波
img1_DETAIL=img1.filter(ImageFilter.DETAIL)
#EDGE_ENHANCE:边界增强滤波
img1_EDGE_ENHANCE=img1.filter(ImageFilter.EDGE_ENHANCE)
#EDGE_ENHANCE_MORE:边界增强滤波(程度更深)
img1_EDGE_ENHANCE_MORE=img1.filter(ImageFilter.EDGE_ENHANCE_MORE)
#EMBOSS浮雕
img1_EMBOSS=img1.filter(ImageFilter.EMBOSS)
#FIND_EDGES:寻找边界滤波
img1_FIND_EDGES=img1.filter(ImageFilter.FIND_EDGES)
#SMOOTH:平滑滤波
img1_SMOOTH=img1.filter(ImageFilter.SMOOTH)
#SMOOTH_MORE:平滑滤波(程度更深)
img1_SMOOTH_MORE=img1.filter(ImageFilter.SMOOTH_MORE)
#SHARPEN:锐化滤波
img1_SHARPEN=img1.filter(ImageFilter.SHARPEN)
#CONTOUR:轮廓滤波
img1_CONTOUR=img1.filter(ImageFilter.CONTOUR)
#拼接
img_output.paste(img1,(0,0))
img_output.paste(img1_GaussianBlur,(w,0))
img_output.paste(img1_BLUR,(2*w,0))
img_output.paste(img1_DETAIL,(0,h))
img_output.paste(img1_EDGE_ENHANCE,(w,h))
img_output.paste(img1_EDGE_ENHANCE_MORE,(2*w,h))
img_output.paste(img1_EMBOSS,(0,2*h))
img_output.paste(img1_FIND_EDGES,(w,2*h))
img_output.paste(img1_SMOOTH,(2*w,2*h))
img_output.paste(img1_SMOOTH_MORE,(0,3*h))
img_output.paste(img1_SHARPEN,(w,3*h))
img_output.paste(img1_CONTOUR,(2*w,3*h))
img_output.show()
result:
I don’t want to learn anymore, I’m going to play games, and I will continue in two days
Keep going
(8) Image overall operation
from PIL import ImageEnhance,Image
im1=Image.open('kiki.jpg')
out=im1.point(lambda i:i*2)#图片整体变亮
out.show()
B. ImageChops module
(1) Add pictures
ImageChops.add(im1,im2,scale=1.0,offset=0)
Calculation formula:
out=((im1+im2)/scale+offset)
from PIL import ImageChops,Image
im1=Image.open('kiki.jpg')
im2=Image.open('niki.jpg')
out=ImageChops.add(im1,im2,1,0)
out.show()
(2) Picture subtraction
ImageChops.subtract(im1,im2,scale=1.0,offset=0)
Calculation formula:
out=((im1-im2)/scale+offset)
(3) The picture becomes darker
ImageChops.darker(im1,im2)
Compare the pixels of the two pictures, take the smaller value of the corresponding pixel value and keep it, thereby removing the bright part
from PIL import ImageChops,Image
im1=Image.open('kiki.jpg')
im2=Image.open('niki.jpg')
out=ImageChops.darker(im1,im2)
out.show()
(4) The picture becomes brighter
ImageChops.lighter(im1,im2)
Compare the pixels of the two pictures, take the larger value of the corresponding pixel value and keep it, so as to remove the dark part
from PIL import ImageChops,Image
im1=Image.open('kiki.jpg')
im2=Image.open('niki.jpg')
out=ImageChops.lighter(im1,im2)
out.show()
(5) Screen function
ImageChops.screen(im1,im2)
Invert the color first and then superimpose, similar to projecting two slides onto one screen with two projectors
Calculation formula:
out=MAX-((MAX-im1)*(MAX-im2)/MAX)
from PIL import ImageChops,Image
im1=Image.open('kiki.jpg')
im2=Image.open('niki.jpg')
out=ImageChops.screen(im1,im2)
out.show()
(6) Inverse color function
ImageChops.invert(im1)
Calculation formula: out=255-im1
from PIL import ImageChops,Image
im1=Image.open('kiki.jpg')
out=ImageChops.invert(im1)
out.show()
(7) Comparison function
ImageChops.difference(im1,im2)
Do subtraction operation to take absolute value
Calculation formula:
abs(im1-im2)
from PIL import ImageChops,Image
im1=Image.open('kiki.jpg')
im2=Image.open('niki.jpg')
out=ImageChops.difference(im1,im2)
out.show()
B. ImageEnhance module (image enhancement)
Instructions:
image_enhance=ImageEnhance.XXX(img) (Get XXX adjuster)
im=image_enhance.enhance(0~2) 0~1 weaken, 1~2 strengthen
(1) Get the color adjuster
ImageEnhance.Color(im)
(2) Get the contrast adjuster
ImageEnhance.Contrast(im)
(3) Get the brightness adjuster
ImageEnhance.Brightness(im)
(4) Obtain the sharpness adjuster
ImageEnhancd.Sharpness(im)
from PIL import ImageEnhance,Image
im1=Image.open('kiki.jpg')
im1.thumbnail((im1.size[0]/3,im1.size[1]/3))
w,h=im1.size
out=Image.new('RGB',(3*w,4*h))
#获取色彩调整器对象
im_color=ImageEnhance.Color(im1)
im_color_a=im_color.enhance(1.5)
im_color_b=im_color.enhance(0.5)
#获取对比度调整器对象
im_contrast=ImageEnhance.Contrast(im1)
im_contrast_a=im_contrast.enhance(1.5)
im_contrast_b=im_contrast.enhance(0.5)
#获取亮度调整器对象
im_brightness=ImageEnhance.Brightness(im1)
im_brightness_a=im_brightness.enhance(1.5)
im_brightness_b=im_brightness.enhance(0.5)
#获取锐度调整器对象
im_sharpness=ImageEnhance.Sharpness(im1)
im_sharpness_a=im_sharpness.enhance(1.7)
im_sharpness_b=im_sharpness.enhance(0.2)
out.paste(im1,(0,0))
out.paste(im_color_a,(w,0))
out.paste(im_color_b,(2*w,0))
out.paste(im1,(0,h))
out.paste(im_contrast_a,(w,h))
out.paste(im_contrast_b,(2*w,h))
out.paste(im1,(0,2*h))
out.paste(im_brightness_a,(w,2*h))
out.paste(im_brightness_b,(2*w,2*h))
out.paste(im1,(0,3*h))
out.paste(im_sharpness_a,(w,3*h))
out.paste(im_sharpness_b,(2*w,3*h))
out.show()
C.ImagDraw module (image drawing)
Instructions:
drawObject = ImageDraw.Draw(blank)
Function: draw two-dimensional image
from PIL import Image, ImageDraw
img = Image.new('RGBA', (200, 200), 'white')
idraw = ImageDraw.Draw(img)
idraw.rectangle((10, 10, 100, 100), fill='blue')
img.save('D:\\rectangle.png')
D. ImagFont module
Function: verification code function
# -*- coding: utf-8 -*-
# __author__: Pad0y
from PIL import Image, ImageDraw, ImageFont
from random import choice, randint, randrange
import string
# 候选字符集,大小写字母+数字
chrs = string.ascii_letters + string.digits
def selected_chrs(length):
"""
返回length个随机字符串
:param length:
:return:
"""
result = ''.join(choice(chrs) for _ in range(length))
return result
def get_color():
"""
设置随机颜色
:return:
"""
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
return (r, g, b)
def main(size=(200, 100), chrNumber=6, bgcolor=(255, 255, 255)):
"""
定义图片大小,验证码长度,背景颜色
:param size:
:param chrNumber:
:param bgcolor:
:return:
"""
# 创建空白图像和绘图对象
image_tmp = Image.new('RGB', size, bgcolor)
draw = ImageDraw.Draw(image_tmp)
# 生成并计算随机字符的宽度和高度
text = selected_chrs(chrNumber)
font = ImageFont.truetype('c:\\windows\\fonts\\simkai.ttf', 48) # 选定一款系统字体
width, height = draw.textsize(text, font)
if width + 2*chrNumber > size[0] or height > size[1]:
print('Size Error!')
return
# 绘制字符串
startX = 0
width_eachchr = width // chrNumber # 计算每个字符宽度
for i in range(chrNumber):
startX += width_eachchr + 1
position = (startX, (size[1]-height)//2+randint(-10, 10)) # 字符坐标, Y坐标上下浮动
draw.text(xy=position, text=text[i], font=font, fill=get_color()) # 绘制函数
# 对像素位置进行微调,实现验证码扭曲效果
img_final = Image.new('RGB', size, bgcolor)
pixels_final = img_final.load()
pixels_tmp = image_tmp.load()
for y in range(size[1]):
offset = randint(-1, 0) # randint()相当于闭区间[x,y]
for x in range(size[0]):
newx = x + offset # 像素微调
if newx >= size[0]:
newx = size[0] - 1
elif newx < 0:
newx = 0
pixels_final[newx, y] = pixels_tmp[x, y]
# 绘制随机颜色随机位置的干扰像素
draw = ImageDraw.Draw(img_final)
for i in range(int(size[0]*size[1]*0.07)): # 7%密度的干扰像素
draw.point((randrange(size[0]), randrange(size[1])), fill=get_color()) # randrange取值范围是左开右闭
# 绘制随机干扰线,这里设置为8条
for i in range(8):
start = (0, randrange(size[1]))
end = (size[0], randrange(size[1]))
draw.line([start, end], fill=get_color(), width=1)
# 绘制随机弧线
for i in range(8):
start = (-50, -50) # 起始位置在外边看起来才会像弧线
end = (size[0]+10, randint(0, size[1]+10))
draw.arc(start+end, 0, 360, fill=get_color())
# 保存图片
img_final.save('Veri_code.jpg')
img_final.show()
if __name__ == '__main__':
main((200, 100), 6, (255, 255, 255))