您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页用python简单处理图片(2):图像通道几何变换裁剪

用python简单处理图片(2):图像通道几何变换裁剪

来源:华佗小知识
⽤python简单处理图⽚(2):图像通道⼏何变换裁剪

⼀、图像通道1、彩⾊图像转灰度图

from PIL import Image

import matplotlib.pyplot as pltimg=Image.open('d:/ex.jpg')gray=img.convert('L')plt.figure(\"beauty\")

plt.imshow(gray,cmap='gray')plt.axis('off')plt.show()

使⽤函数convert()来进⾏转换,它是图像实例对象的⼀个⽅法,接受⼀个 mode 参数,⽤以指定⼀种⾊彩模式,mode 的取值可以是如下⼏种:

· 1 (1-bit pixels, black and white, stored with one pixel per byte)· L (8-bit pixels, black and white)

· P (8-bit pixels, mapped to any other mode using a colour palette)· RGB (3x8-bit pixels, true colour)

· RGBA (4x8-bit pixels, true colour with transparency mask)· CMYK (4x8-bit pixels, colour separation)· YCbCr (3x8-bit pixels, colour video format)· I (32-bit signed integer pixels)· F (32-bit floating point pixels)2、通道分离与合并

from PIL import Image

import matplotlib.pyplot as plt

img=Image.open('d:/ex.jpg') #打开图像gray=img.convert('L') #转换成灰度r,g,b=img.split() #分离三通道

pic=Image.merge('RGB',(r,g,b)) #合并三通道plt.figure(\"beauty\")

plt.subplot(2,3,1), plt.title('origin')plt.imshow(img),plt.axis('off')plt.subplot(2,3,2), plt.title('gray')

plt.imshow(gray,cmap='gray'),plt.axis('off')plt.subplot(2,3,3), plt.title('merge')plt.imshow(pic),plt.axis('off')plt.subplot(2,3,4), plt.title('r')

plt.imshow(r,cmap='gray'),plt.axis('off')plt.subplot(2,3,5), plt.title('g')

plt.imshow(g,cmap='gray'),plt.axis('off')plt.subplot(2,3,6), plt.title('b')

plt.imshow(b,cmap='gray'),plt.axis('off')plt.show()

⼆、裁剪图⽚

从原图⽚中裁剪感兴趣区域(roi),裁剪区域由4-tuple决定,该tuple中信息为(left, upper, right, lower)。 Pillow左边系统的原点(0,0)为图⽚的左上⾓。坐标中的数字单位为像素点。

from PIL import Image

import matplotlib.pyplot as plt

img=Image.open('d:/ex.jpg') #打开图像plt.figure(\"beauty\")

plt.subplot(1,2,1), plt.title('origin')plt.imshow(img),plt.axis('off')box=(80,100,260,300)roi=img.crop(box)

plt.subplot(1,2,2), plt.title('roi')plt.imshow(roi),plt.axis('off')plt.show()

⽤plot绘制显⽰出图⽚后,将⿏标移动到图⽚上,会在右下⾓出现当前点的坐标,以及像素值。三、⼏何变换

Image类有resize()、rotate()和transpose()⽅法进⾏⼏何变换。 1、图像的缩放和旋转

dst = img.resize((128, 128))

dst = img.rotate(45) # 顺时针⾓度表⽰

2、转换图像

dst = im.transpose(Image.FLIP_LEFT_RIGHT) #左右互换dst = im.transpose(Image.FLIP_TOP_BOTTOM) #上下互换dst = im.transpose(Image.ROTATE_90) #顺时针旋转dst = im.transpose(Image.ROTATE_180)dst = im.transpose(Image.ROTATE_270)

transpose()和rotate()没有性能差别。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务