在一系列轴图像中添加每个像素

2024-06-25 23:57:47 发布

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

我目前正在尝试使用python为给定的图像数据系列创建颜色图。在使用了一个名为Powderday的软件之后,我在存储器中存储了一个名为“merger.070”的文件。新建.rtout.image“这是我在代码第18行中调用的)一系列大约35幅图像,每幅图像都包含特定星系合并特定波长的通量信息。我想通过这些图像中的每一个循环,创建一个最终的图像,基本上是这些图像中的每一个加起来,这样我就不用在一个图像中有几个单一波长的图像,而是在一个图像中有一系列的波长。你知道吗

为了做到这一点,我想通过每一个图像循环,保存在一个最终的图像波长地图,并不断添加后续图像到这最后一个。唯一的问题是,每次我找到单波长图像时,都会得到一个轴图像,据我所知,它不具备与另一个图像合并的功能。到目前为止,我在网上发现最好的解决方案是从图像创建一个numpy数组,但是我也找不到get\u image函数是否来自matplotlib.image文件将接受AxeImage参数以将其转换为这样的数组。我的代码在下面。你知道吗

重要的行位于: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)

Tags: 文件the图像imageimportmatplotlibvalueas
1条回答
网友
1楼 · 发布于 2024-06-25 23:57:47

首先,不能将Matplotlib AxesImage加载到NumPy数组中。你知道吗

我不在您的领域,但基于Hyperion documentationfor ModelOutput.get_image()我相信get_image()会从您的代码中以NumPy数组的形式返回图像数据:

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

查看type(image)来验证这一点。如果我是对的,你应该看看numpy.ndarray。你知道吗

如果是这样,那么finalImg = mpimg.imread(cax)是多余的…您已经在image变量中将图像作为NumPy数组加载。你知道吗

现在,如果您想将数据作为单独的通道加载到单个ndarray对象中,那么您可以在get_image()完成。打印image.ndim应该显示3(您有一个三维图像数组),其中img.shape(y_axis_length, x_axis_length, number_of_channels)。你知道吗

基于你如何措辞你的问题,虽然我认为你想把这些通道组合成一个单一的强度值为每一个像素的总和,在每个通道的强度。此操作将产生形状为(y_axis_length, x_axis_length)的二维灰度图像。为了理解我的意思,请考虑一下我为您准备的以下示例:

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()

fig2

相关问题 更多 >