gpt4 book ai didi

python - 有没有一种更快的方法使用 numpy 中的矢量化操作从大型二维数组中恢复图像

转载 作者:行者123 更新时间:2023-12-01 03:17:35 25 4
gpt4 key购买 nike

我有一个尺寸为 n x 1008 的大型二维数组(通常为 0.5 到 2GB)。该数组包含多个图像,数组中的值实际上是像素值。基本上恢复这些图像的方法如下

  1. 开始迭代数组。
  2. 取前 260 行,即您将拥有 260*1008=262080 个值。
  3. 对于第 261 行,仅采用前 64 个值(该行中的其余值都是垃圾值)。因此现在我们有 262144 个像素值。
  4. 将所有这些值转储到一维数组中,例如 dump 并执行 np.reshape(dump, (512,512))) 来获取图像。请注意,512x512=262144
  5. 从第 262 行开始再次重复相同的操作。

这是我的解决方案

counter=0
dump=np.array([], dtype=np.uint16)
#pixelDat is the array shaped n x 1008 containing the pixel values
for j in xrange(len(pixelDat)):
#Check if it is the last row for a particular image
if(j == (260*(counter+1)+ counter)):
counter += 1
dump=np.append(dump, pixelDat[j][:64])
#Reshape dump to form the image and write it to a fits file
hdu = fits.PrimaryHDU(np.reshape(dump, (512,512)))
hdu.writeto('img'+str("{0:0>4}".format(counter))+'.fits', clobber=True)
#Clear dump to enable formation of next image
dump=np.array([], dtype=np.uint16)
else:
dump=np.append(dump, pixelDat[j])

我一直想知道是否有办法加快整个过程。我首先想到的是使用向量化 numpy 运算。但是我不太确定如何在这种情况下应用它。

P.S:不要担心 Fitting 和 hdu 部分。它只是为我的图像创建一个 .fits 文件。

最佳答案

这是使用扁平化和np.split的尝试。它避免了复制数据。

def chop_up(pixelDat):
sh = pixelDat.shape
try:
# since the array is large we do not want a copy
# the next line will succeed only if we can reshape in-place
pixelDat.shape = -1
except:
return False # user must resort to other method
N = len(pixelDat)
split = (np.arange(0, N, 261*1008)[:, None] + (0, 512*512)).ravel()[1:]
if split[-1] > N:
split = split[:-2]
result = [x.reshape(512,512) for x in np.split(pixelDat, split) if len(x) == 512*512]
pixelDat.shape = sh
return result

关于python - 有没有一种更快的方法使用 numpy 中的矢量化操作从大型二维数组中恢复图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42318267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com