19.操作图像
1)计算机图像基础
a)颜色和RGBA值
RGBA:红绿蓝和透明度 0-255
ImageColor.getcolor(颜色名称,‘RGBA’) 返回RGBA元组
b)坐标和Box元组
图像像素以(x,y)坐标指定
图块以Box4数元组指定,左上和右下(x1,y1,x2,y2)
2)用pillow操作图像
from PIL import Image
a)Image数据类型
Image.open(fname) 打开图像文件
size 图像大小 width height
filename 图像文件名称
format 图像格式 format_description 图像格式描述
Image.convert(‘RGB’) 转换图像格式
!png格式是RGBA ,jpeg格式是RGB.png格式不能存成jpg,要转换
Image.save(fname) 存储图像文件
Image.new(‘RGBA’,(width,height),bgcolor) 新生成一个空图像文件.
b)裁剪图像
Image.crop((x1,y1,x2,y2))
c)复制粘贴到其他图像
Image.copy() 图像复制
Image.paste(sIm,(x,y)) 图像粘贴
测试程序:test_1901.py 用猫头像覆盖猫身图片
from PIL import Image
import os
os.chdir('d:/temp')
catIm = Image.open('catz.png')
faceIm = catIm.crop((335,345,565,560))
catImWidth,catImHeight = catIm.size
faceImWidth,faceImHeight = faceIm.size
catCopyIm = catIm.copy()
for left in range(0,catImWidth,faceImWidth):
for top in range(0,catImHeight,faceImHeight):
print(left,top)
catCopyIm.paste(faceIm,(left,top))
catCopyIm.save('catz_cp.png')
d)调整图像大小
Image.resize((newwidth,newheigth))
e)旋转图像
旋转图像Image.rorate(angle,expand=True|False)
翻转图像Image.transpose()
FLIP_LEFT_RIGHT:左右翻转 FLIP_TOP_BOTTOM:上下翻转
f)更改单个像素
测试程序:test_1902.py
from PIL import Image
import os
os.chdir('d:/temp')
im = Image.new('RGBA',(100,100))
im.getpixel((0,0))
print('B color 0,0:' + str(im.getpixel((0,0))))
for x in range(100):
for y in range(50):
im.putpixel((x,y),(210,210,210))
from PIL import ImageColor
for x in range(100):
for y in range(50,100):
im.putpixel((x,y),ImageColor.getcolor('darkgray','RGBA'))
print('U color 0,0:' + str(im.getpixel((0,0))))
print('U color 0,50:' + str(im.getpixel((0,50))))
im.save('putPixel.png')
Image.getpixel((x,y)) 取指定坐标的颜色值
Image.putpixel((x,y),(RGB)) 设定指定坐标的颜色值
3)项目:添加徽标
测试程序:test_1903.py
!! 徽标素材图太大,改成100像素为好
#! python3
# resizeandAddLogopy - Resizes all images in current working directory to fit
# in a 300*300 square,and adds catlogo.png to the lower-right corner.
import os
from PIL import Image
os.chdir('d:/temp')
SQUARE_FIT_SIZE = 800
LOGO_FILENAME = 'catlogo.png'
logoIm = Image.open(LOGO_FILENAME)
logoWidth,logoHeight = logoIm.size
os.makedirs('withLogo',exist_ok=True)
# Loop over all file in the working directory
for filename in os.listdir('.'):
if not (filename.endswith('.png') or filename.endswith('.jpg')) or filename == LOGO_FILENAME:
continue # skip non-image files and the logo file itself
im = Image.open(filename)
width,height = im.size
# Check if image needs to be resized.
if width > height:
height = int((SQUARE_FIT_SIZE/width)*height)
width = SQUARE_FIT_SIZE
else:
width = int((SQUARE_FIT_SIZE / height) * width)
height = SQUARE_FIT_SIZE
# Resize th image.
print('Resizing %s ...' % (filename))
im = im.resize((width,height))
# Add the logo.
print('Adding logo to %s...' % (filename))
im.paste(logoIm,(width - logoWidth,height- logoHeight),logoIm)
# Save changes.
im.save(os.path.join('withLogo',filename))
4)在图像上绘画
ImageDraw模块
draw = ImageDraw.Draw(im=Image.new())
a)绘制形状
点:point(xy,fill)
线:line(xy,fill,width)
矩形:rectangle(xy,fill,outline)
椭圆:ellipse(xy,fill,outline)
多边形:polygon(xy,fill,outline)
测试程序:test_1904.py
from PIL import Image,ImageDraw,ImageFont
import os
os.chdir('d:/temp')
im = Image.new('RGBA',(800,800),'white')
draw = ImageDraw.Draw(im)
draw.line([(0,0),(799,0),(799,799),(0,799),(0,0)],fill='brown',width=10)
draw.rectangle((20,30,240,240),fill='blue')
draw.ellipse((480,120,640,240),fill='red',outline='blue')
draw.polygon(((228,348),(316,248),(372,340),(480,360),(412,452)),fill='brown')
for i in range(400,800,40):
draw.line([(i,0),(800,i-400)],fill='green')
# text draw
draw.text((60,600),'Hello',fill='purple')
fontsFolder = 'FONT_FOLDER001'
#arialFont = ImageFont.truetype(os.path.join(fontsFolder,'arial.ttf'),128)
textFont = ImageFont.truetype('FRSCRIPT.TTF',90)
draw.text((400,600),'Howdy',fill='red',font=textFont)
im.save('drawing.png')
b)绘制文本
文本:text((x,y),text ,fill,font)
font = ImageFont.truetype(‘***.ttf’,charsize)
不必带入字体目录,系统会自己找相关目录,字体文件名大小写敏感。
windows系统的字体文件在c:\windows\fonts目录下。
5)项目:在硬盘上识别照片文件夹
测试程序:test_1905.py
#! python3
# Import modules and write comments to describe this program.
import os,PIL
from PIL import Image
for foldername,subfolders,filenames in os.walk('d:\\'):
numPhotoFiles = 0
numNonPhotoFiles = 0
for filename in filenames:
if not (filename.endswith('.png') or filename.endswith('.jpg')):
numNonPhotoFiles += 1
continue
try:
im = Image.open(os.path.join(foldername,filename))
except PIL.UnidentifiedImageError:
numNonPhotoFiles += 1
continue
width,height = im.size
if width > 1000 and height > 1000:
numPhotoFiles += 1
else:
numNonPhotoFiles += 1
if numPhotoFiles > numNonPhotoFiles:
print('Folder %s is Photo Directory(%s:%s)' % (foldername,numPhotoFiles,numNonPhotoFiles))