numpy缩放图片/调整图片大小

遇到numpy需要调整大小的情况,暂时没找到好方法,所以调用了PIL库,但是,我处理的矩阵格式是float类型。很是麻烦,写了一个转换代码,用到了3个函数

def transfer(image):
    """
    data is transfered to 0-255,将矩阵转成uint8型,并保留转换回来的范围。这儿使用的是线性变换。
    transfer() & re_transfer() will be used in PIL.Image
    PIL.image was used in resize() & jitter()
    :param image:
    :return: its range of every channel
    """
    data = image.copy()
    min_max = []  # range of channls
    h, w, c = data.shape
    for i in range(c):
        min_d, max_d = (np.min(data[:, :, i]), np.max(data[:, :, i]))
        min_max.append((min_d, max_d))
        zone = max_d - min_d
        if zone < 0.1:
            zone = 0.1
        data[:, :, i] = 1.0 * (data[:, :, i] - min_d) / zone * 255
    data = data.astype('uint8')
    return data, min_max


def re_transfer(image, min_max):
    """
    transfer to float ones再将数据转换为float类型,但是类型的精度不能得到保障
    :param image:
    :param min_max:
    :return:
    """
    data = image.copy()
    data = data.astype('float16')
    h, w, c = data.shape
    for i in range(c):
        min_d, max_d = min_max[i]
        min_now, max_now = (np.min(data[:, :, i]), np.max(data[:, :, i]))
        zone = (max_now - min_now)
        if zone < 0.1:
            zone = 0.1

        data[:, :, i] = 1.0 * (data[:, :, i] - min_now) / zone * (max_d - min_d) + min_d

    return data


#调用了PIL图片库
import numpy as np
from PIL import Image

def resize(data,sz):
    """
    将data转成sz,sz是tuple类型,为大小
    """
    image, min_max = transfer(data)
    image = Image.fromarray(image)
    image = image.resize(sz)
    image = np.array(image)
    image = re_transfer(image, min_max)
    return image

继续寻找有没有实现这个函数的库,找到一个相似的,但是还没有做验证。

from skimage import transform,data
dst=transform.resize(img, (80, 60))

skimage没有用过,在一篇博客上找到的,现在先贴下来:python数字图像处理(7):图像的形变与缩放 :https://www.cnblogs.com/denny402/p/5124152.html

你可能感兴趣的:(python学习,numpy,图片缩放,调整图片大小)