首页 > 解决方案 > 如何在一维中变形/缩放 3 维 numpy 数组?

问题描述

我想在一维中变形/缩放一个三维 numpy 数组。我将在 2D 中可视化我的问题:

我有原始图像,它是一个 2D numpy 数组:

在此处输入图像描述

然后我想将它变形/缩放为维度 0 或水平维度中的某个因素:

在此处输入图像描述

对于PIL图像,有很多解决方案,例如在pytorch中,但是如果我有一个 numpy 形状数组 (w, h, d) = (288, 288, 468) 怎么办?我想以 1.04 的因子对宽度进行上采样,例如到 (299, 288, 468)。每个单元格包含一个介于 0 和 1 之间的标准化数字。

我不确定,如果我只是不寻找正确的词汇,如果我尝试在线搜索。因此,纠正我的问题也会有所帮助。或者告诉我这个问题的数学背景,然后我可以自己写代码。

谢谢!

标签: python-3.xnumpyimage-processingscalescaletransform

解决方案


您可以沿特定轴重复数组的次数等于ceil(factor)where factor > 1,然后在拉伸维度上均匀间隔索引以选择int(factor * old_length)元素。这不执行任何类型的插值,而只是重复一些元素:

import math

import cv2
import numpy as np
from scipy.ndimage import imread

img = imread('/tmp/example.png')
print(img.shape)  # (512, 512)

axis = 1
factor = 1.25

stretched = np.repeat(img, math.ceil(factor), axis=axis)
print(stretched.shape)  # (512, 1024)

indices = np.linspace(0, stretched.shape[axis] - 1, int(img.shape[axis] * factor))
indices = np.rint(indices).astype(int)

result = np.take(stretched, indices, axis=axis)
print(result.shape)  # (512, 640)

cv2.imwrite('/tmp/stretched.png', result)

这是结果(左边是原始的example.png,右边是stretched.png):

例子


推荐阅读