将float NumPy数组转换为big endian

时间:2015-07-21 18:06:27

标签: python python-2.7 numpy

我编写了一个脚本,最后我需要将float64类型的数组转换为big endian int(> 2i):

[[ 0.92702157  1.03092008  0.9072934  ...,  0.71617331  1.02524888
    1.07284994]
[ 0.99573712  0.96416766  0.9230931  ...,  0.66935196  0.64930711
0.5357821 ]
[ 0.98846306  1.03608056  0.79976885 ...,  0.69383804  0.62434976
0.88219911]
..., 
[ 0.91196013  0.87880101  0.97145563 ...,  0.79110817  1.19651477
0.98244941]
[ 1.0129829   0.81045263  0.95434107 ...,  0.99752385  1.08271169
1.12872492]
[ 0.94037117  0.81365084  0.94384051 ...,  0.82754351  1.03742172  1.]]

我怎么能这样做?

这是完整的脚本

import numpy as np
import pyfits
from matplotlib import pyplot as plt
import glob
import os
import re
from struct import unpack,pack

global numbers
numbers=re.compile(r'(\d+)')


def numericalSort(value):
    parts = numbers.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts

dark=sorted(glob.glob(' *.fits'),key=numericalSort)
flat=sorted(glob.glob('/ *.fits'),key=numericalSort)
img=sorted(glob.glob('/ *.fits'),key=numericalSort)

#dark
sumd0 = pyfits.open(dark[0])
sumdd=sumd0[0].data
sumdd = sumdd.astype(float,copy=False)

for i in range(1,len(dark)):
    sumdi=pyfits.open(dark[i])
    sumdi=sumdi[0].data
    sumdd=sumdd+sumdi.astype(float, copy=False)


dd=sumdd/len(dark)


#flat
sumf0 = pyfits.open(flat[0])
sumff=sumf0[0].data
sumff = sumff.astype(float, copy=False)

for i in range(1,len(flat)):
    sumfi=pyfits.open(flat[i])
    sumfi=sumfi[0].data
    sumff=sumff+sumfi.astype(float,copy=False)

ff=sumff/len(flat)


df=(ff-dd)
maxx=np.max(df)
df=np.clip(df,1,maxx)


for n in range(len(img)):
    im=pyfits.open(img[n])
    imgg=im[0].data
    header=im[0].header
    imgg=imgg.astype(float,copy=False)
    x,y=im[0].shape
    m=np.max(imgg)
    imgg=np.clip((imgg-dd),1,m)
    imgg=imgg/df
    imgg=np.clip(imgg,0.5,1.5)


    #print imgg.dtype
    #imgg=imgg[200:950,150:1250]
    #imgg=imgg[::-1,:y]
     hdu = pyfits.PrimaryHDU(imgg,header)
     hdulist = pyfits.HDUList([hdu])
     hdulist.writeto('/c'+img[n][48:])
     plt.imshow(imgg,cmap=plt.cm.Greys_r)
#plt.savefig('/+'.png')
plt.show()

在最后9行,我需要将数组imgg从float64转换为> i2

1 个答案:

答案 0 :(得分:1)

>>> import numpy as np
>>> big_end = bytes(chr(0) + chr(1) + chr(3) + chr(2), 'utf-8')
>>> np.ndarray(shape=(2,),dtype='>i2', buffer=big_end)
array([  1, 770], dtype=int16)

另见:Byte-swapping