python Pillow图像处理方法汇总

yipeiwu_com5年前Python基础

这篇文章主要介绍了python Pillow图像处理方法汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Pillow中文文档:https://pillow-cn.readthedocs.io/zh_CN/latest/handbook/tutorial.html

安装:pip install pillow

操作图像:

#!/usr/bin/env python3
# _*_ coding utf-8 _*_

__author__ = 'nxz'

from PIL import Image, ImageFilter
from time import sleep

# 打开一个jpg图像文件
im = Image.open('test.jpg')
w, h = im.size #
print('图片的宽:%s,和高:%s' % (w, h))

# 图片缩放
im.thumbnail((w // 2, h // 2))
w, h = im.size
print(w, h)

# 缩放之后的图片重新保存
im.save('thumbnail.jpg', 'jpeg')

# 其他功能:切片、旋转、滤镜、输出文字、调色板

# 模糊效果
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg','jpeg')

截屏:

from PIL import ImageGrab
from time import sleep

m = int(input("请输入想截屏多少次:"))
n = 1
while n <= m:
  sleep(0.02)
  im = ImageGrab.grab()
  local = (r'%s.jpg' % (n))
  im.save(local, 'jpeg')
  n = n + 1

转换文件到JPEG:

'''
将指定路径下的图片后缀改为 “.jpg” 格式
'''

from PIL import Image
import os, sys

for infile in sys.argv[1:]:
  f, e = os.path.splitext(infile)
  outfile = f + '.jpg'
  if infile != outfile:
    try:
      Image.open(infile).save(outfile)
    except Exception as exc:
      print(exc)

GIF动图:

"""
GIf动图
"""

from PIL import Image

im = Image.open('test.jpg')
images = []
images.append(Image.open('blur.png'))
images.append(Image.open('test.jpg'))
im.save('gif.gif', save_all=True, append_image=images, loop=1, duration=1, comment=b'aaaabbb')

几何变换:

#简单的集合变换
out = im.resize((128, 128))

#旋转图像
out = im.transpose(Image.FLIP_LEFT_RIGHT) #翻转
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out = im.transpose(Image.ROTATE_90)
out = im.transpose(Image.ROTATE_180) #旋转180°
out = im.transpose(Image.ROTATE_270) #旋转270°

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 链接和操作 memcache方法

1,打开memcached服务 memcached -m 10 -p 12000 2,使用python-memcached模块,进行简单的链接和存取数据 import me...

Sanic框架配置操作分析

本文实例讲述了Sanic框架配置操作。分享给大家供大家参考,具体如下: 简介 Sanic是一个类似Flask的Python 3.5+ Web服务器,它的写入速度非常快。除了Flask之外...

Python数据分析之真实IP请求Pandas详解

前言 pandas 是基于 Numpy 构建的含有更高级数据结构和工具的数据分析包类似于 Numpy 的核心是 ndarray,pandas 也是围绕着 Series 和 DataFra...

Python中py文件转换成exe可执行文件的方法

Python中py文件转换成exe可执行文件的方法

一、背景 今天闲着无事,写了一个小小的Python脚本程序,然后给同学炫耀的时候,发现每次都得拉着其他人过来看着自己的电脑屏幕,感觉不是很爽,然后我想着网上肯定有关于Python脚本转...

教你用Python创建微信聊天机器人

教你用Python创建微信聊天机器人

最近研究微信API,发现个非常好用的python库:wxpy。wxpy基于itchat,使用了 Web 微信的通讯协议,实现了微信登录、收发消息、搜索好友、数据统计等功能。 这里我们就来...