python-3.x - 如何在一维中变形/缩放 3 维 numpy 数组?
问题描述
我想在一维中变形/缩放一个三维 numpy 数组。我将在 2D 中可视化我的问题:
我有原始图像,它是一个 2D numpy 数组:
然后我想将它变形/缩放为维度 0 或水平维度中的某个因素:
对于PIL图像,有很多解决方案,例如在pytorch中,但是如果我有一个 numpy 形状数组 (w, h, d) = (288, 288, 468) 怎么办?我想以 1.04 的因子对宽度进行上采样,例如到 (299, 288, 468)。每个单元格包含一个介于 0 和 1 之间的标准化数字。
我不确定,如果我只是不寻找正确的词汇,如果我尝试在线搜索。因此,纠正我的问题也会有所帮助。或者告诉我这个问题的数学背景,然后我可以自己写代码。
谢谢!
解决方案
您可以沿特定轴重复数组的次数等于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
):
推荐阅读
- wagtail - 将片段注入 Wagtail StreamField 接口
- c# - 创建 SHA 哈希并在源移动位置时进行比较
- qiskit - 如何在 5qubit 量子电路中更改输入 qubits(q3 和 q4)
- python - 有没有更有效的方法来查找丢失的整数?
- java - 使用 Java 9 模块和 Maven 进行 IntelliJ 依赖管理 - 我做错了什么?
- c++ - 以下代码中嵌入的“new”是否会导致内存泄漏?
- python - Python正在将末尾帖子编号处的零点添加到字符串
- mongodb - Mongo - 查找包含点的键的记录
- sql - 如何使用演员表的价值进行更新?
- javascript - 如何在 react-native 中实现刮刮卡/视图?