Python PIL图像处理:核心概念解析与等比例压缩裁剪实战
本文深入解析Python PIL库中的通道、模式、尺寸、坐标系统及滤波器等核心概念,详细对比NEAREST、BILINEAR等四种采样滤波器。通过完整实例代码演示如何利用PIL实现图像的等比例压缩与指定区域裁剪,帮助开发者掌握高效的图片处理技巧。
在PIL库中,理解几个基础概念对于高效进行图像处理至关重要。
首先是通道(bands),它指的是图像的波段数量。例如,标准的RGB图像包含三个通道,而灰度图像则只有一个通道。
以常见的RGB图像为例进行说明:
>>>from PIL import Image
>>>im = Image.open('*.jpg') # 打开一张RGB图像
>>>im_bands = im.g
etbands() # 获取RGB三个波段
>>>len(im_bands)
>>>print im_bands[0,1,2] # 输出RGB三个值
其次是模式(mode),该属性定义了图像的具体类型以及每个像素所占用的位宽。PIL主要支持9种不同的模式:
>>> im.mode
① 1:1位像素,表示黑和白,但是存储的时候每个像素存储为8bit。 ② L:8位像素,表示黑和白。 ③ P:8位像素,使用调色板映射到其他模式。 ④ RGB:3x8位像素,为真彩色。 ⑤ RGBA:4x8位像素,有透明通道的真彩色。 ⑥ CMYK:4x8位像素,颜色分离。 ⑦ YCbCr:3x8位像素,彩色视频格式。 ⑧ I:32位整型像素。 ⑨ F:32位浮点型像素。
第三是尺寸(size),通过该属性可以获取图像在水平方向(宽度)和垂直方向(高度)上的像素数量。
>>> im.size()
第四是坐标系统(coordinate system),PIL采用笛卡尔像素坐标体系。
在该体系中,坐标原点(0, 0)位于图像的左上角。
需要特别注意,坐标值代表的是像素的角点位置;因此,位于坐标(0, 0)处的像素,其实际中心点坐标为(0.5, 0.5)。
第五是调色板(palette)。
当图像模式为“P”时,表示使用调色板模式,即通过索引一个颜色调色板来为每个像素定义具体的颜色值。
第六是信息(info),该属性通常包含图像的元数据,如EXIF信息等。
>>> im.info() # 返回值为字典对象
第七是滤波器(filters),这是一类几何操作,用于将多个输入像素映射为一个输出像素,常用于图像缩放或旋转时的重采样。
PIL提供了4种不同的采样滤波器供选择:
① NEAREST:最近邻滤波。该方法直接从输入图像中选取距离输出像素最近的原始像素值作为结果,速度最快但质量较低。
② BILINEAR:双线性插值滤波。该方法在输入图像的2x2像素矩阵上进行线性插值计算,平衡了速度与质量。
③ BICUBIC:双立方插值滤波。该方法在输入图像的4x4像素矩阵上进行立方插值,能生成更平滑的边缘。
④ ANTIALIAS:平滑滤波。这是一种高质量的重采样滤波器,它考虑所有可能影响输出像素的输入像素,通过加权计算得出最终像素值,通常用于缩小图像以保持清晰度。
在PIL中,im.resize()和im.thumbnail()方法均支持使用上述滤波器来控制缩放效果。
方法一:resize(size, filter=None),用于调整图像尺寸,可指定滤波器。
>>> from PIL import Image
>>> im = Image.open('*.jpg')
>>> im.size
>>> im_resize = im.resize((256,256)) #default 情况下是NEAREST插值方法
>>> im_resize0 = im.resize((256,256), Image.BILINEAR)
>>> im_resize0.size
>>> im_resize1 = im.resize((256,256), Image.BICUBIC)
>>> im_resize2 = im.resize((256,256), Image.ANTIALIAS)
方法二:im.thumbnail(size, filter=None),用于创建图像的缩略图,保持宽高比不变。
关于PIL的相关基础介绍至此结束。下面分享一个使用PIL进行图像处理(包括等比例压缩和裁剪)的完整实例代码,具体如下:
#coding:utf-8
'''
python图片处理
@author:fc_lamp
@blog:http://fc-lamp.blog.163.com/
'''
import Image as image
#等比例压缩图片
def resizeImg(**args):
args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}
arg = {}
for key in args_key:
if key in args:
arg[key] = args[key]
im = image.open(arg['ori_img'])
ori_w,ori_h = im.size
widthRatio = heightRatio = None
ratio = 1
if (ori_w and ori_w > arg['dst_w']) or (ori_h and ori_h > arg['dst_h']):
if arg['dst_w'] and ori_w > arg['dst_w']:
widthRatio = float(arg['dst_w']) / ori_w #正确获取小数的方式
if arg['dst_h'] and ori_h > arg['dst_h']:
heightRatio = float(arg['dst_h']) / ori_h
if widthRatio and heightRatio:
if widthRatio < heightRatio:
ratio = widthRatio
else:
ratio = heightRatio
if widthRatio and not heightRatio:
ratio = widthRatio
if heightRatio and not widthRatio:
ratio = heightRatio
newWidth = int(ori_w * ratio)
newHeight = int(ori_h * ratio)
else:
newWidth = ori_w
newHeight = ori_h
im.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])
'''
image.ANTIALIAS还有如下值:
NEAREST: use nearest neighbour
BILINEAR: linear interpolation in a 2x2 environment
BICUBIC:cubic spline interpolation in a 4x4 environment
ANTIALIAS:best down-sizing filter
'''
#裁剪压缩图片
def clipResizeImg(**args):
args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}
arg = {}
for key in args_key:
if key in args:
arg[key] = args[key]
im = image.open(arg['ori_img'])
ori_w,ori_h = im.size
dst_scale = float(arg['dst_h']) / arg['dst_w'] #目标高宽比
ori_scale = float(ori_h) / ori_w #原高宽比
if ori_scale >= dst_scale:
#过高
width = ori_w
height = int(width*dst_scale)
x = 0
y = (ori_h - height) / 3
else:
#过宽
height = ori_h
width = int(height*dst_scale)
x = (ori_w - width) / 2
y = 0
#裁剪
box = (x,y,width+x,height+y)
#这里的参数可以这么认为:从某图的(x,y)坐标开始截,截到(width+x,height+y)坐标
#所包围的图像,crop方法与php中的imagecopy方法大为不一样
newIm = im.crop(box)
im = None
#压缩
ratio = float(arg['dst_w']) / width
newWidth = int(width * ratio)
newHeight = int(height * ratio)
newIm.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])
#水印(这里仅为图片水印)
def waterMark(**args):
args_key = {'ori_img':'','dst_img':'','mark_img':'','water_opt':''}
arg = {}
for key in args_key:
if key in args:
arg[key] = args[key]
im = image.open(arg['ori_img'])
ori_w,ori_h = im.size
mark_im = image.open(arg['mark_img'])
mark_w,mark_h = mark_im.size
option ={'leftup':(0,0),'rightup':(ori_w-mark_w,0),'leftlow':(0,ori_h-mark_h),
'rightlow':(ori_w-mark_w,ori_h-mark_h)
}
im.paste(mark_im,option[arg['water_opt']],mark_im.convert('RGBA'))
im.save(arg['dst_img'])
#Demon
#源图片
ori_img = 'D:/tt.jpg'
#水印标
mark_img = 'D:/mark.png'
#水印位置(右下)
water_opt = 'rightlow'
#目标图片
dst_img = 'D:/python_2.jpg'
#目标图片大小
dst_w = 94
dst_h = 94
#保存的图片质量
save_q = 35
#裁剪压缩
clipResizeImg(ori_img=ori_img,dst_img=dst_img,dst_w=dst_w,dst_h=dst_h,save_q = save_q)
#等比例压缩
#resizeImg(ori_img=ori_img,dst_img=dst_img,dst_w=dst_w,dst_h=dst_h,save_q=save_q)
#水印
#waterMark(ori_img=ori_img,dst_img=dst_img,mark_img=mark_img,water_opt=water_opt)
总结
以上就是本文关于Python使用PIL进行图像处理(等比例压缩、裁剪)实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:
Python内置模块turtle绘图详解
Python中pygal绘制雷达图代码分享
python自动裁剪图像代码分享
如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









