基于Jupyter 完成实验四:Python图像处理库(Pillow教程)

1、Image类

from PIL import Image
im=Image.open("lena.png")
from __future__ import print_function
print(im.format, im.size, im.mode)
PNG (1081, 573) RGB
im.show()

在这里插入图片描述

2、图片转成jpg格式

from PIL import Image


def IsValidImage(img_path):
    """
    判断文件是否为有效(完整)的图片
    :param img_path:图片路径
    :return:True:有效 False:无效
    """
    bValid = True
    try:
        Image.open(img_path).verify()
    except:
        bValid = False
    return bValid


def transimg(img_path):
    """
    转换图片格式
    :param img_path:图片路径
    :return: True:成功 False:失败
    """
    if IsValidImage(img_path):
        try:
            str = img_path.rsplit(".", 1)
            output_img_path = str[0] + ".jpg"
            print(output_img_path)
            im = Image.open(img_path)
            im.save(output_img_path)
            return True
        except:
            return False
    else:
        return False


if __name__ == '__main__':
    img_path = 'lena.png'
    print(transimg(img_path))
lena.jpg
True
im = Image.open("lena.jpg")
im.show()

在这里插入图片描述
在这里插入图片描述

3、创建缩略图

#导入包
from PIL import Image
import os

#获取文件大小
def get_size(file):
    # 获取文件大小:KB
    size = os.path.getsize(file)
    return size / 1024

#拼接输出文件地址
def get_outfile(infile, outfile):
    if outfile:
        return outfile
    dir, suffix = os.path.splitext(infile)
    outfile = '{}-out{}'.format(dir, suffix)
    return outfile

#压缩文件到指定大小
def compress_image(infile, outfile='', mb=128, step=10, quality=80):
    """不改变图片尺寸压缩到指定大小
    :param infile: 压缩源文件
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标,KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址,压缩文件大小
    """
    o_size = get_size(infile)
    if o_size <= mb:
        return infile
    outfile = get_outfile(infile, outfile)
    while o_size > mb:
        im = Image.open(infile)
        im.save(outfile, quality=quality)
        if quality - step < 0:
            break
        quality -= step
        o_size = get_size(outfile)
    return outfile, get_size(outfile)

#修改图片尺寸
def resize_image(infile, outfile='', x_s=240):
    """修改图片尺寸
    :param infile: 图片源文件
    :param outfile: 重设尺寸文件保存地址
    :param x_s: 设置的宽度
    :return:
    """
    im = Image.open(infile)
    x, y = im.size
    y_s = int(y * x_s / x)
    out = im.resize((x_s, y_s), Image.ANTIALIAS)
    outfile = get_outfile(infile, outfile)
    out.save(outfile)


if __name__ == '__main__':
    compress_image(r"lena.png")
    resize_image(r"lena.png")

左边是原图,右边是缩放后的
在这里插入图片描述

4、确定图片属性

from __future__ import print_function
import sys
from PIL import Image

for infile in sys.argv[1:]:
    try:
        with Image.open(infile) as im:
            print(infile, im.format, "%dx%d" % im.size, im.mode)
    except IOError:
        pass
im=Image.open("lena.png")
print(im.format, im.size, im.mode)
PNG (1081, 573) RGB

5、裁剪、粘贴、与合并图片

#1)从图片中复制子图像
from PIL import Image
import matplotlib.pyplot as plt
im= Image.open("lena.png")
im= im.crop((200,200,500,500))
im.save("lena_crop.png") 
im.show()

在这里插入图片描述

#2)处理子图,粘贴回原图
from PIL import Image
im1=Image.open("lena.png")
im2=Image.open("lena_crop.png")
im1.paste(im2,(200,200))
im1.save("lena_paste.png")
im1.show()

在这里插入图片描述

#3)分离和合并通道
#图片分离
import numpy as np;
import cv2;             #导入opencv模块
 
image=cv2.imread("lena.png");#读取要处理的图片
B,G,R = cv2.split(image);                       #分离出图片的B,R,G颜色通道
cv2.imshow("RED",R);                            #显示三通道的值都为R值时d图片
cv2.imshow("GREEN",G);                          #显示三通道的值都为G值时d图片
cv2.imshow("BLUE",B);                           #显示三通道的值都为B值时d图片
cv2.waitKey(0);                                 #不让程序突然结束

在这里插入图片描述

#使用merge()函数将某一颜色通道(如R)与零矩阵合并,形成(R,0,0)从而显示只有红色通道的图
import numpy as np;
import cv2;             #导入opencv模块
 
image=cv2.imread("lena.png");#读取要处理的图片
B,G,R = cv2.split(image);                       #分离出图片的B,R,G颜色通道
zeros = np.zeros(image.shape[:2],dtype="uint8");#创建与image相同大小的零矩阵
cv2.imshow("BLUE",cv2.merge([B,zeros,zeros]));#显示 (B,0,0)图像
cv2.imshow("GREEN",cv2.merge([zeros,G,zeros]));#显示(0,G,0)图像
cv2.imshow("RED",cv2.merge([zeros,zeros,R]));#显示(0,0,R)图像
cv2.waitKey(0);

在这里插入图片描述

#图像合并
import numpy as np;
import cv2;             #导入opencv模块
 
image=cv2.imread("lena.png");#读取要处理的图片
B,G,R = cv2.split(image);                       #分离出图片的B,R,G颜色通道
zeros = np.zeros(image.shape[:2],dtype="uint8");#创建与image相同大小的零矩阵
cv2.imshow("MERGE",cv2.merge([B,G,R]));
cv2.waitKey(0);

在这里插入图片描述

6、几何变换

1)简单几何变换,顺时针旋转45°
from PIL import Image
im=Image.open("lena.png")
out = im.resize((128, 128))
out = im.rotate(45) # 顺时针角度表示
out.show()

在这里插入图片描述

2)置换图像
from PIL import Image
im=Image.open("lena.png")
out1 = im.transpose(Image.FLIP_LEFT_RIGHT)
out1.show()
out2 = im.transpose(Image.FLIP_TOP_BOTTOM)
out2.show()
out3 = im.transpose(Image.ROTATE_90)
out3.show()
out4 = im.transpose(Image.ROTATE_180)
out4.show()
out5 = im.transpose(Image.ROTATE_270)
out5.show()

在这里插入图片描述

3)模式转换
from PIL import Image
im=Image.open("lena.png")
im = Image.open('lena.png').convert('L')
im.show()

在这里插入图片描述

7、图像增强

1)Filter
from PIL import ImageFilter
im=Image.open("lena.png")
out = im.filter(ImageFilter.DETAIL) 
im.show()

在这里插入图片描述

2)像素点处理
from PIL import ImageFilter
im=Image.open("lena.png")
# multiply each pixel by 1.5
out = im.point(lambda i: i * 1.5)
im.show()

在这里插入图片描述

3)高级图片增强
from PIL import ImageEnhance
from PIL import ImageFilter
im=Image.open("lena.png")
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")

在这里插入图片描述

8、更多读取图片方法(可选)

#draft读取图片
from __future__ import print_function
im = Image.open("lena.png")
print("original =", im.mode, im.size)
im.draft("L", (100, 100))
print("draft =", im.mode, im.size)
im.show()

在这里插入图片描述
original = RGB (1081, 573)
draft = RGB (1081, 573)

  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值