在numpy中有没有一种更快的方法可以使用矢量化操作从一个大的2D数组中恢复图像

2024-10-03 19:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个尺寸为nx1008的大二维阵列(通常为0.5到2GB)。此数组包含多个图像,数组中的值实际上是像素值。基本上恢复这些图像的步骤如下

  1. 开始迭代数组。你知道吗
  2. 取前260行,即260*1008=262080。你知道吗
  3. 对于第261行,只取前64个值(该行中的其余值是垃圾值)。因此,现在我们有262144像素的值。你知道吗
  4. 将所有这些值转储到一个1-D数组中,然后说Dump和donp.重塑(dump,(512512)))获取图像。注意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操作。但是我不太清楚如何在这种情况下应用它。你知道吗

注:不要担心配合和hdu部分。它只是为我的图像创建一个.fits文件。你知道吗


Tags: theto图像imagenpcounter像素数组
1条回答
网友
1楼 · 发布于 2024-10-03 19:29:57

下面是一个使用展平和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

相关问题 更多 >