简体   繁体   English

使用numpy和pyfits在Python中缩小图像数组的更快方法

[英]Faster method of scaling down image array in Python using numpy and pyfits

I'm using Python 2.7.3 with numpy and pyfits to process scientific FITS files. 我正在将Python 2.7.3与numpy和pyfits配合使用,以处理科学的FITS文件。 I would like to work on the images at half or one quarter resolution for the sake of speed, and have this code: 为了提高速度,我想以一半或四分之一的分辨率处理图像,并使用以下代码:

# Read red image
hdulist = pyfits.open(red_fn)
img_data = hdulist[0].data
hdulist.close()
img_data_r = numpy.array(img_data, dtype=float)
# Scale it down to one quarter size
my=[]
for line in img_data_r[::4]:
    myline=[]
    for item in line[::4]:
        myline.append(item)
    my.append(myline)
img_data_r = my

This works, but I wonder if there is a faster, more native way to reduce the array. 这行得通,但是我想知道是否有更快,更本地化的方法来减少阵列。 The reductions should happen as early as possible, the idea being that the data that will be processed is of minimal acceptable size. 减少应该尽早进行,其想法是要处理的数据具有最小的可接受大小。 If there was a way of reading a reduced dataset with pyfits, that would be ideal. 如果有一种方法可以读取带有pyfit的精简数据集,那将是理想的选择。 But such a method doesn't seem to exist (correct me if I'm wrong). 但是这种方法似乎不存在(如果我错了,请纠正我)。 How about numpy? numpy怎么样? Or scipy/math/anything else? 还是scipy / math /其他?

The data array you get from pyfits already is a NumPy array. 您从pyfits获得的数据数组已经是NumPy数组。 You don't need to create one from it. 您无需从中创建一个。 Moerover, you can simply do the downsampling in a single step: 此外,您只需一步即可进行下采样:

img_data_r = hdulist[0].data[::4, ::4]

This won't copy the data, but rather simply copy a new view with different strides. 这不会复制数据,而只是简单地复制具有不同跨度的新视图。 If you need the down-sampled image as a contiguous array, use numpy.ascontiguousarray() . 如果需要将向下采样的图像作为连续数组,请使用numpy.ascontiguousarray()

This method of downsampling only keeps one in sixteen pixels, and completely drops the information in all the other pixels. 这种下采样方法仅保留16个像素中的一个,而完全丢弃所有其他像素中的信息。 If you need higher-quality downsampling, rather than doing it in your code, you are probably better off to downsample your FITS files using Imagemagick. 如果您需要更高质量的下采样,而不是在代码中进行,则最好使用Imagemagick对FITS文件进行下采样。 This will also reduce the time it takes to read the files from disk. 这还将减少从磁盘读取文件所需的时间。

To convert all your FITS files in the current directory in place (warning: big versions get overwritten), you could use 要就地转换当前目录中的所有FITS文件(警告:大版本将被覆盖),您可以使用

mogrify -resize 25% *.fits

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM