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 代码效率的方法
Jul 03 Python
python虚拟环境virualenv的安装与使用
Dec 18 Python
使用Python3制作TCP端口扫描器
Apr 17 Python
Python字符串拼接六种方法介绍
Dec 18 Python
zookeeper python接口实例详解
Jan 18 Python
Python面向对象之继承代码详解
Jan 29 Python
Python实现定时执行任务的三种方式简单示例
Mar 30 Python
pyqt5 使用cv2 显示图片,摄像头的实例
Jun 27 Python
python打开使用的方法
Sep 30 Python
使用Python测试Ping主机IP和某端口是否开放的实例
Dec 17 Python
教你用python控制安卓手机
May 13 Python
python ansible自动化运维工具执行流程
Jun 24 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变量可用字符
2014/05/28 PHP
使用CodeIgniter的类库做图片上传
2014/06/12 PHP
php对xml文件的增删改查操作实现方法分析
2017/05/19 PHP
多广告投放代码 推荐
2006/11/13 Javascript
JavaScript setTimeout和setInterval的使用方法 说明
2010/03/25 Javascript
Extjs4 关于Store的一些操作(加载/回调/添加)
2013/04/18 Javascript
Javascript监视变量变化的方法
2015/06/09 Javascript
基于jQuery实现的美观星级评论打分组件代码
2015/10/30 Javascript
javascript下拉列表中显示树形菜单的实现方法
2015/11/17 Javascript
jQuery实现页面顶部显示的进度条效果完整实例
2015/12/09 Javascript
BootStrap中Table分页插件使用详解
2016/10/09 Javascript
nodejs获取微信小程序带参数二维码实现代码
2017/04/12 NodeJs
从零开始学习Node.js系列教程六:EventEmitter发送和接收事件的方法示例
2017/04/13 Javascript
解决vue2.x中数据渲染以及vuex缓存的问题
2017/07/13 Javascript
浅谈JS函数节流防抖
2017/10/18 Javascript
bootstrap动态调用select下拉框的实例代码
2018/08/09 Javascript
利用原生的JavaScript实现简单拼图游戏
2018/11/18 Javascript
小程序rich-text组件如何改变内部img图片样式的方法
2019/05/22 Javascript
Vue 中使用富文本编译器wangEditor3的方法
2019/09/26 Javascript
Vue使用axios引起的后台session不同操作
2020/08/14 Javascript
[02:01]BBC DOTA2国际邀请赛每日综述:八强胜者组鏖战,中国队喜忧参半
2014/07/19 DOTA
Python爬取京东的商品分类与链接
2016/08/26 Python
Python实现的购物车功能示例
2018/02/11 Python
解决pycharm运行出错,代码正确结果不显示的问题
2018/11/30 Python
Django 表单模型选择框如何使用分组
2019/05/16 Python
python tkinter图形界面代码统计工具
2019/09/18 Python
python安装第三方库如xlrd的方法
2020/10/31 Python
css3教程之倾斜页面
2014/01/27 HTML / CSS
canvas使用注意点总结
2013/07/19 HTML / CSS
澳大利亚的奢侈品牌:Oroton
2016/08/26 全球购物
农村结婚典礼司仪主持词
2014/03/14 职场文书
党员对照检查材料
2014/09/22 职场文书
信访维稳承诺书
2015/05/04 职场文书
教师个人师德工作总结2015
2015/05/12 职场文书
社区党务工作总结2015
2015/05/19 职场文书
python中出现invalid syntax报错的几种原因分析
2022/02/12 Python