Numpy:将不均匀的一维数组重塑为二维数组以进行字节绘图
Numpy: reshape uneven 1D array to 2D array for byte plotting
这对每个人来说可能太容易了,但正如我在主题中提到的,有没有办法将不均匀的一维 numpy 数组重塑为二维 numpy 数组?
当我说不均匀的一维数组时,形状是 (34191,),这是使用 np.fromfile[= 读取二进制文件得到的10=]
我在这里尝试做的实际事情实际上是 display/plot 我正在读取的二进制文件作为图像(如字节图)。
所以将文件读取为一维 numpy 数组,将其转换为二维数组,display/plot/将其保存为灰度图像。
欢迎任何想法
如果我对问题的解释正确,你有一个一维数组,你想将它显示为图像,但你不知道先验什么形状它应该是。
此函数查找数字的 'squarest' 形状(即值最接近的两个因子)。
import numpy as np
def closest_factor_pair(x: int) -> tuple:
"""
Tries to find the pair of factors of x, i.e. the
closest integers to the square root of x.
Example
>>> closest_factor_pair(34191)
(131, 261)
"""
for i in range(int(np.sqrt(x)), 0, -1):
if x % i == 0:
return i, int(x/i)
return None
我们可以用它来猜测数组的大小并显示它:
>>> size = 34191
>>> shape = closest_factor_pair(size)
(131, 261)
如果你有你的数组,你可以重塑它并显示:
import matplotlib.pyplot as plt
arr = np.random.random(size)
plt.matshow(arr.reshape(shape))
给出:
这对每个人来说可能太容易了,但正如我在主题中提到的,有没有办法将不均匀的一维 numpy 数组重塑为二维 numpy 数组? 当我说不均匀的一维数组时,形状是 (34191,),这是使用 np.fromfile[= 读取二进制文件得到的10=]
我在这里尝试做的实际事情实际上是 display/plot 我正在读取的二进制文件作为图像(如字节图)。 所以将文件读取为一维 numpy 数组,将其转换为二维数组,display/plot/将其保存为灰度图像。
欢迎任何想法
如果我对问题的解释正确,你有一个一维数组,你想将它显示为图像,但你不知道先验什么形状它应该是。
此函数查找数字的 'squarest' 形状(即值最接近的两个因子)。
import numpy as np
def closest_factor_pair(x: int) -> tuple:
"""
Tries to find the pair of factors of x, i.e. the
closest integers to the square root of x.
Example
>>> closest_factor_pair(34191)
(131, 261)
"""
for i in range(int(np.sqrt(x)), 0, -1):
if x % i == 0:
return i, int(x/i)
return None
我们可以用它来猜测数组的大小并显示它:
>>> size = 34191
>>> shape = closest_factor_pair(size)
(131, 261)
如果你有你的数组,你可以重塑它并显示:
import matplotlib.pyplot as plt
arr = np.random.random(size)
plt.matshow(arr.reshape(shape))
给出: