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的itchat库实现微信聊天机器人(推荐)

基于python的itchat库实现微信聊天机器人(推荐)

一、开始之前必须安装itchat库 pip install itchat(使用pip必须在电脑的环境变量中添加Python的路径) 或 conda install request 二、开...

对python while循环和双重循环的实例详解

废话不多说,直接上代码吧! #python中,while语句用于循环执行程序,即在某个条件下,循环执行某段程序,以处理需要重复处理的相同任务。 #while是“当型”循环结构。 i=...

Python开发的十个小贴士和技巧及长常犯错误

下面是十个Python中很有用的贴士和技巧。其中一些是初学这门语言常常会犯的错误。 注意:假设我们都用的是Python 3 1. 列表推导式 你有一个list:bag = [1, 2,...

python使用xlrd与xlwt对excel的读写和格式设定

前言 python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。本文主要介绍了python使用xlrd与xlwt对excel的读...

pytorch-神经网络拟合曲线实例

pytorch-神经网络拟合曲线实例

代码已经调通,跑出来的效果如下: # coding=gbk import torch import matplotlib.pyplot as plt from torch.auto...