[AstroPy] astropy.io.fits won't allow me to modify the NAXIS keywords

Daniel Evans d.f.evans at keele.ac.uk
Mon Oct 23 10:56:13 EDT 2017


Dear Sebastien,

> Do you know what would be the best syntax to add a trailing dimension
from a 2D image? I mean, in a clever way without doubling the memory
consumption.

The docs for numpy.reshape() state that the returned object "[...] will be
a new view object if possible; otherwise, it will be a copy.", suggesting
that a change will be done in place if possible. The following test returns
True for me, indicating that the data is not duplicated:

import numpy

foo = numpy.zeros((256, 256))

# "Reshape" foo into a 3D array
bar = foo.reshape((-1, 256, 256))

# If bar is a new view of foo, then they are both referencing the same data
# Therefore, a modification of foo will propogate to bar
foo[0, 0] = 1
print("foo and bar are the same data: ", foo[0, 0] == bar[0, 0, 0])

Regards,
Daniel

On 23 October 2017 at 15:02, Sébastien Bardeau <bardeau at iram.fr> wrote:

> Dear Daniel,
>
>
> On 10/23/2017 03:49 PM, Daniel Evans wrote:
>
> Dear Sebastien,
>
> I suspect you're right that astropy is undoing your modifications as it
> thinks the header no longer matches the data. The solutions I can think of
> for your problem are:
>
> 1. Simply modify the array once read into Python to turn it into a 2D
> array, suitable for matplotlib.pyplot.imshow (or similar). This is
> relatively standard for viewing images in datacubes anyway, and requires
> very little effort in Python:
>
>     a = astropy.io.fits.open(sys.argv[1])
>     image4D = a[0].data
>     a.close()
>
>     image2D = image4D[0, 0]
>     matplotlib.pyplot.imshow(image2D)
>     matplotlib.pyplot.show()
>
> 2. If you do want to modify the fits file, you can convert the array from
> 4D to 2D, and reinsert this into the file. astropy will update the header
> to match:
>
>     a = astropy.io.fits.open(sys.argv[1], mode = "update")
>     a[0].data = a[0].data[0, 0]
>     a.close()
>
>
> I was focusing on editing the header, but actually "editing" the data
> works great! Thanks.
>
> Do you know what would be the best syntax to add a trailing dimension from
> a 2D image? I mean, in a clever way without doubling the memory consumption.
>
>
>
> John ZuHone - the issue is presumably that matplotlib is being asked to
> display a 2D image, but is being passed a 4D array - I've done this many
> times with 3D datacubes!
>
>
> @ John ZuHone: I am not a Matplotlib user (I am in charge of
> reading/writing the FITS files), and I had just a comment about a
> Matplotlib error without more details. But Daniel is probably right here.
>
> Thanks,
>
> Sebastien
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/astropy/attachments/20171023/a7783e3e/attachment.html>


More information about the AstroPy mailing list