图像处理_Image

1.       安装

   输入 pip install PIL报错:

  ERROR: Could not find a version that satisfies the requirement PIL (from versions: none)
  ERROR: No matching distribution found for PIL

解决方案:

Python3中Pillow源自PIL(在2中使用)

(1)       python -m pip install Pillow

(2)       pip install path\文件名 文件名为在网址:

https://www.lfd.uci.edu/~gohlke/pythonlibs/

中下载对应的模块。

使用(1)时报错:

ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.

超时问题,延长时间:

python -m pip --default-timeout=100 install -U Pillow

注:pillow是PIL(Python成像库)的一个分支,不再被维护。所以,为了保持向后兼容性,往往使用旧的模块名称——PIL,即引用模块,直接使用import PIL

2.       功能

以快速访问几种基本像素类型表示的图像数据为核心,能对图像做归档处理、显示图像、常见的图像处理(变换、点操作、滤波、颜色等等)。

1.1         Image模块

from PIL import Image

# 打开一个图像

Picture = Image.open("C:\\Users\\sue\\Pictures\\test.png")

print(Picture)

# 返回图像实例的属性

print("图像格式:{};图像模式:{};图像大小:{}。".format(Picture.format,Picture.mode,Picture.size))

# 查看实例,show是暂时存放了一个临时文件,存在效率问题

Picture.show()

# 实例的方法:

# 1.保存图片,以及转换图片格式,无法转换报转换错误:svae(存储文件名[,存储文件格式:可省略由扩展名决定])

Picture.save("C:\\Users\\sue\\Pictures\\test2.png","PNG")

Picture.save("C:\\Users\\sue\\Pictures\\test3.jpg")

try:

    Picture.save("C:\\Users\\sue\\Pictures\\test4.jpg","JPG") #明确格式后,加转换格式反而报错KeyError

except:

    print("cannot convert")

# 2.制作缩略图 p.thumbnail((x,y)),参数为一个元组

width,heighth = Picture.size

Picture.thumbnail((width/2,heighth/2))

Picture.save("C:\\Users\\sue\\Pictures\\test2.png","PNG")

# 3.裁剪图片:p.crop((x,y,x+m,y+n)),x,y为以图片左上角为原点,向下为y轴,向右为x轴;

#   m,n为想要裁剪的长宽

#  在原图(20,10)的位置开始裁剪一个长为200,宽100的图

PCrop = Picture.crop((20,40,20+200,10+100))

PCrop.show()

# 4.变形和粘贴

#  p.transpose(Image.XX):其中XX=FLIP_LEFT_RIGHT(左右镜像);FLIP_TOP_BOTTOM(上下镜像)

#    ROTATE_90(逆时针旋转90度);RATATE_180(逆时针旋转180度);ROTATAE_270;

#    TRANSPOSE(像素矩阵转置,空间变换);TRANVERSE(空间变换)

#  p.paste(p1,(x,y,x+m,y+n)),将图片p1粘贴到p的(x,y)处,占长m宽n的大小。后面两个不写就是完全粘贴p1

from PIL import Image

# 将人物图像的左边镜像颠倒,复制到右边,右边原样复制到左边

def P_transpose(P):

    x,y = P.size

    pleft = P.crop((0,0,x//2,y))

    pright = P.crop((x//2,0,x,y))

    pleft = pleft.transpose(Image.FLIP_TOP_BOTTOM)

    P.paste(pright,(0,0,x//2,y))

    P.paste(pleft,(x//2,0,x,y))

    P.show()

Picture = Image.open("C:\\Users\\sue\\Pictures\\人物.png")

P_transpose(P)

# 5.调整尺寸

# resize((m,n))

# rotate(sigma),逆时针调整角度

猜你喜欢

转载自www.cnblogs.com/wljlxx/p/11695390.html