2017-02-23 12 views
0

現在、pythonを使用して、与えられた一連の画像のカラープロットを作成しようとしています。 Powderdayというソフトウェアを使用した後、私は自分のコードの18行目で呼び出された "merger.070.new.rtout.image"という名前のファイルに格納されています。特定の銀河合併の特定の波長。私はそれらの画像のそれぞれをループし、本質的にそれらの画像のそれぞれが最終的な画像を生成し、いくつかの単一波長画像の代わりに、一連の波長を1つの画像に有するようにしたい。AxesImagesの各ピクセルを追加する

これを行うには、各画像をループし、波長マップを最終画像に保存し、後の画像をこの最終画像に追加し続けます。唯一の問題は、私が知っている限り、別の画像とマージする機能を持たない単一波長画像を見つけるたびにAxesImageを取得していることです。私はこれまでのところ、これまで最高の解決策は、画像からnumpy配列を作成することですが、matplotlib.imageのget_image関数がAxesImageパラメータを受け入れて、そのようなアレイ。私のコードは以下の通りです。

重要な行は次のとおりです。42〜45ここで、finalImgを初期化してループ内で「反復」できるようにします。 47 - 61ここで私は各イメージを繰り返しています。

また、私が読んでいるB_JohnsonとB_thruputファイルには、.imageファイルにある波長と対応するスループットに関する情報が含まれています。実際の現実のフィルタを正確にシミュレートするためには、各波長で見つかったフラックスにそのスループットを乗算したいからです。

この情報は、この問題の良い背景を提供します。私はまだPythonには非常に新しいです。これらの画像をすべて追加する最良の方法は何ですか?以下

import numpy as np 
import matplotlib 
matplotlib.use('Agg') 
import matplotlib.pyplot as plt 
import matplotlib.image as mpimg 
from hyperion.model import ModelOutput 
from astropy.cosmology import Planck13 
import astropy.units as u 


# ------------------------ 
# modifiable header 
# ------------------------ 

filters = np.loadtxt('B_Johnson.txt') 
thru = np.loadtxt('B_thruput.txt', dtype='double') 

ライン18:以下

m = ModelOutput('/home/sss274/Work/Outputs/diskMerger/70/merger.070new.rtout.image') 
redshift=2 
image_width = 200 #kpc 

# ------------------------ 


distance = Planck13.luminosity_distance(redshift).cgs.value 


# Extract the image for the first inclination, and scale to 300pc. We 
# have to specify group=1 as there is no image in group 0. 
image = m.get_image(distance=distance, units='mJy') 

# Open figure and create axes 
fig = plt.figure() 

ax = fig.add_subplot(111) 

#calculate image width in kpc 
w = image.x_max * u.cm 
w = w.to(u.kpc) 

ライン42:

cax = ax.imshow(image.val[0,:,:,(np.argmin(np.abs(3600 - image.wav)))]*0, 
       cmap = plt.cm.spectral, origin='lower', extent=[-w.value, w.value, -w.value, w.value]) 

finalImg = mpimg.imread(cax) 

ライン47 - ループ内の61:

for idx, fil in enumerate(filters): 
    wav = fil 

    #find nearest wavelength 
    iwav = np.argmin(np.abs(wav - image.wav)) 

    #find the throughput to multiply found flux by throughput 
    throughput = thru[idx] 

    #plot the beast 

    cax = ax.imshow((image.val[0,:, :, iwav])*throughput, 
        cmap = plt.cm.spectral, origin='lower', extent=[-w.value, w.value, -w.value, w.value]) 

    finalImg += mpimg.imread(cax) 

    plt.xlim([-image_width,image_width]) 
    plt.ylim([-image_width,image_width]) 


# Finalize the plot 
ax.tick_params(axis='both', which='major', labelsize=10) 
ax.set_xlabel('x kpc') 
ax.set_ylabel('y kpc') 

plt.colorbar(cax,label='Flux (mJy)',format='%.0e') 

fig.savefig('pd_image_bj.png', bbox_inches='tight',dpi=150) 

答えて

1

まず、ロードできませんMatplotlib AxesImageをNumPy配列に変換します。

私はあなたの分野ではないのですが、私はあなたのコードから次の行でnumpyの配列としてget_image()戻って画像データを信じるModelOutput.get_image()ためHyperion documentationに基づいて:これを確認するtype(image)

image = m.get_image(distance=distance, units='mJy') 

ルック。私が正しい場合は、numpy.ndarrayが表示されます。

この場合、finalImg = mpimg.imread(cax)は余分です... image変数にNumPy配列としてイメージを読み込んでいます。

データを1つのndarrayオブジェクトに別々のチャネルとしてロードする場合は、get_image()で完了します。 image.ndimを印刷する場合は、img.shape(y_axis_length, x_axis_length, number_of_channels)3(3次元画像アレイを使用)と表示されます。

あなたの質問をどのように表現したかに基づいて、各チャンネルの強度の合計を取ることによって、これらのチャンネルを各ピクセルの単一の輝度値に結合したいと考えています。この操作は、形状(y_axis_length, x_axis_length)の2次元グレースケール画像を生成する。

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.cbook import get_sample_data 

# load example image file 
image_file = get_sample_data("grace_hopper.png", asfileobj=True) 

# read example image file to NumPy array 
image_array = plt.imread(image_file) 

# show `image_array` as color (RGB) image 
fig = plt.figure() 
plt.imshow(image_array) 
plt.tight_layout() 
plt.axis('off') # turns off x and y-axis ticks 
plt.show() 

fig

# since the image is color (RGB), slice into individual channels 
# to illustrate adding image arrays 
c1 = image_array[:, :, 0] 
c2 = image_array[:, :, 1] 
c3 = image_array[:, :, 2] 

# define empty array with same shape as one image slice 
# this will become the final image result 
new_array = np.zeros_like(c1) 

# visualize empty array 
fig0 = plt.figure() 
plt.imshow(new_array, cmap='gray') 
plt.tight_layout() 
plt.axis('off') 
plt.show() 

fig0

# visualize distinct image slices (RGB image has three color channels) 
# one at a time to illustrate differences between images 
fig1, ax = plt.subplots(nrows=1, ncols=3) 
for img, a in zip([c1, c2, c3], ax): 
    a.imshow(img, cmap='gray') 
    a.axis('off') 

    # iteratively add image slices to `new_array` 
    # while we are iterating over the slices 
    new_array += img 

plt.tight_layout() 
plt.show() 

fig1

# visualize end result of iteratively adding image slices to `new_array` 
fig2 = plt.figure() 
plt.imshow(new_array, cmap='gray') 
plt.axis('off') 
plt.tight_layout() 
plt.show() 
:私が何を意味するかを確認するには、私はあなたのために策定されている次の例を考えてみてください。 10

fig2

+0

ありがとうございました!色情報を保持せずに空の配列を作成する方法はありますか?あるいは、私は最初のイメージをforループの外に初期化して、ループ内でそれを追加しますか? –

+0

気にしないで!私はnp.empty_likeを使用することができ、ちょうどそれを見つけた。 –

+0

問題ありません!うん、np.empty_likeは空の配列を初期化します。この例では、np.zeros_likeを使用しています。配列は0で埋められています。 – Brian

関連する問題