python图像处理模块Pillow的学习详解


Posted in Python onOctober 09, 2019

今天抽空学习了一下之前了解过的pillow库,以前看到的记得这个库可以给图片上加文字加数字,还可以将图片转化成字符画,不过一直没有找时间去学习一下这个模块,由于放假不用训练,所以就瞎搞了一下

0、工欲善其事,必先利其器

关于pillow库的安装有几种方式

0、使用pip安装

$ pip install pillow

1、使用easy_install

$ easy_install pillow

2、通过pycharm安装

1、学习并使用pillow库

#导入模块
from PIL import Image
#读取文件
img = Image.open('test.jpg')
#保存文件
#img.save(filename,format)
img.save(filename,"JPEG")
#获取图片大小
(width,height) = img.size
#获取图片的源格式
img_format = img.format
#获取图片模式,有三种模式:L(灰度图像),RGB(真彩色)和CMYK(pre-press图像)
img_mode = img.mode
#图片模式的转换
img = img.convert("L") #转化成灰度图像
#获取每个坐标的像素点的RGB值
r,g,b = img.getpixel((j,i))
#重设图片大小
img = img.resize(width,height)
#创建缩略图
img.thumbnail(size)

2、实战演练

其实应该很容易想到,如果要达到这种效果,应该能想得到就是获取图上每一点的RGB值,然后根据这三种值确定这一点采用什么字符,其实根据RGB来确定的交灰值,所以可以将图片转化成灰度图片,来直接获取每一点的灰度,或者通过灰度的转换公式来使得RGB三值转化成灰度

#coding:utf-8
from PIL import Image
#要索引的字符列表
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
length = len(ascii_char)
img = Image.open('03.jpg')  #读取图像文件
(width,height) = img.size
img = img.resize((int(width*0.9),int(height*0.5))) #对图像进行一定缩小
print(img.size)
def convert(img):
 img = img.convert("L") # 转为灰度图像
 txt = ""
 for i in range(img.size[1]):
  for j in range(img.size[0]):
   gray = img.getpixel((j, i))  # 获取每个坐标像素点的灰度
   unit = 256.0 / length
   txt += ascii_char[int(gray / unit)] #获取对应坐标的字符值
  txt += '\n'
 return txt

def convert1(img):
 txt = ""
 for i in range(img.size[1]):
  for j in range(img.size[0]):
   r,g,b = img.getpixel((j, i))   #获取每个坐标像素点的rgb值
   gray = int(r * 0.299 + g * 0.587 + b * 0.114) #通过灰度转换公式获取灰度
   unit = (256.0+1)/length
   txt += ascii_char[int(gray / unit)] # 获取对应坐标的字符值
  txt += '\n'
 return txt

txt = convert(img)
f = open("03_convert.txt","w")
f.write(txt)   #存储到文件中
f.close()

给图片加上文字(福利预警,前方有福利!!!!)

#coding:utf-8
from PIL import Image,ImageDraw,ImageFont

#http://font.chinaz.com/zhongwenziti.html 字体下载网站

img = Image.open('PDD01.jpg')
draw = ImageDraw.Draw(img)
myfont = ImageFont.truetype('HYLiuZiHeiJ.ttf',size=80)
fillcolor = 'pink'
(width, height) = img.size
#第一个参数是加入字体的坐标
#第二个参数是文字内容
#第三个参数是字体格式
#第四个参数是字体颜色
draw.text((40,100),u'萌萌哒',font=myfont,fill=fillcolor)
img.save('modfiy_pdd01.jpg','jpeg')

给图片加上数字

这个大家应该见过的,就是有些头像的左上角的那个小红圈加上白色的数字,其实方法和上面那个加文字的差不多 

讲道理,我还不如用ps,移坐标移到要死要死的

#coding:utf-8
from PIL import Image,ImageDraw,ImageFont
img = Image.open("03.jpg")
draw = ImageDraw.Draw(img)
myfont = ImageFont.truetype(u"时光体.ttf",50)
(width,height) = img.size
draw.ellipse((width-40,0,width,40),fill="red",outline="red") #在图上画一个圆
draw.text((width-30,-8),'1',font=myfont,fill='white')
img.save('03_modify.jpg')

生成4位随机验证码

#coding:utf-8
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random
"""
创建四位数的验证码
"""
#产生随机验证码内容
def rndTxt():
 txt = []
 txt.append(random.randint(97,123))  #大写字母
 txt.append(random.randint(65,90))  #小写字母
 txt.append(random.randint(48,57))  #数字
 return chr(txt[random.randint(0,2)])

#随机颜色(背景)
def rndColor1():
 return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

#随机颜色(字体)
def rndColor2():
 return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

#240x60:
width = 60*4
height = 60
img = Image.new('RGB',(width,height),(255,255,255))
font = ImageFont.truetype(u'时光体.ttf',36)
draw = ImageDraw.Draw(img)
#填充每个像素
for x in range(width):
 for y in range(height):
  draw.point((x,y),fill=rndColor1())

#输出文字
for txt in range(4):
 draw.text((60*txt+10,10),rndTxt(),font=font,fill=rndColor2())
#模糊化处理
#img = img.filter(ImageFilter.BLUR)
img.save("code.jpg")

学习于:廖雪峰的官方网站

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python通过字典dict判断指定键值是否存在的方法
Mar 21 Python
Pthon批量处理将pdb文件生成dssp文件
Jun 21 Python
python字典DICT类型合并详解
Aug 17 Python
Python二叉树的定义及常用遍历算法分析
Nov 24 Python
Python针对给定列表中元素进行翻转操作的方法分析
Apr 27 Python
Python中 map()函数的用法详解
Jul 10 Python
python中的插值 scipy-interp的实现代码
Jul 23 Python
Python----数据预处理代码实例
Mar 20 Python
Python生成rsa密钥对操作示例
Apr 26 Python
在pycharm中使用matplotlib.pyplot 绘图时报错的解决
Jun 01 Python
python和js交互调用的方法
Jun 23 Python
PyQt5实现多张图片显示并滚动
Jun 11 Python
Python 中pandas索引切片读取数据缺失数据处理问题
Oct 09 #Python
详解python路径拼接os.path.join()函数的用法
Oct 09 #Python
Django Docker容器化部署之Django-Docker本地部署
Oct 09 #Python
Python3实现zip分卷压缩过程解析
Oct 09 #Python
基于Python新建用户并产生随机密码过程解析
Oct 08 #Python
Python小程序 控制鼠标循环点击代码实例
Oct 08 #Python
Python3 无重复字符的最长子串的实现
Oct 08 #Python
You might like
谈谈关于php的优点与缺点
2013/04/11 PHP
深入解析Session是否必须依赖Cookie
2013/08/02 PHP
PHP实现把数字ID转字母ID
2013/08/12 PHP
Yii2.0 RESTful API 基础配置教程详解
2018/12/26 PHP
基于PHP实现微信小程序客服消息功能
2019/08/12 PHP
jQuery使用手册之三 CSS操作
2007/03/24 Javascript
指定js可访问其它域名的cookie的方法
2007/09/18 Javascript
40款非常棒的jQuery 插件和制作教程(系列二)
2011/11/02 Javascript
js获取通过ajax返回的map型的JSONArray的方法
2014/01/09 Javascript
jQuery实现Twitter的自动文字补齐特效
2014/11/28 Javascript
JavaScript构造函数详解
2015/12/27 Javascript
Base64(二进制)图片编码解析及在各种浏览器的兼容性处理
2017/02/09 Javascript
Angular 2 利用Router事件和Title实现动态页面标题的方法
2017/08/23 Javascript
vue+webpack 打包文件 404 页面空白的解决方法
2018/02/28 Javascript
JavaScript模拟实现自由落体效果
2018/08/28 Javascript
js中async函数结合promise的小案例浅析
2019/04/14 Javascript
微信小程序 scroll-view 水平滚动实现过程解析
2019/10/12 Javascript
封装 axios+promise通用请求函数操作
2020/08/11 Javascript
vue 避免变量赋值后双向绑定的操作
2020/11/07 Javascript
pycharm 使用心得(四)显示行号
2014/06/05 Python
python with statement 进行文件操作指南
2014/08/22 Python
用Python实现服务器中只重载被修改的进程的方法
2015/04/30 Python
python使用win32com库播放mp3文件的方法
2015/05/30 Python
Python聚类算法之DBSACN实例分析
2015/11/20 Python
Django如何实现内容缓存示例详解
2017/09/24 Python
通过实例了解Python str()和repr()的区别
2020/01/17 Python
python yield和Generator函数用法详解
2020/02/10 Python
基于Python绘制个人足迹地图
2020/06/01 Python
美国东北部户外服装和设备零售商:Eastern Mountain Sports
2016/10/05 全球购物
什么是Connection-oriented Protocol/Connectionless Protocol面向连接的协议/无连接协议
2012/09/06 面试题
四年大学自我鉴定
2014/02/17 职场文书
2014年环境卫生工作总结
2014/11/24 职场文书
2016幼儿园教师节新闻稿
2015/11/25 职场文书
nginx限制并发连接请求数的方法
2021/04/01 Servers
win11无法添加打印机怎么办? 提示windows无法打开添加打印机的解决办法
2022/04/05 数码科技
Win10防火墙白名单怎么设置?Win10添加防火墙白名单方法
2022/04/06 数码科技