如何将多个NumPy数组嵌入到一个更大的数组中?
如何将两个图像数组嵌入同一张背景图并同时显示
你的代码中两个赋值操作并没有互相覆盖——img1嵌入在背景的左上角(0-400行/列),img2嵌入在(500-600行/列)的位置,两个区域完全不重叠。你觉得第二个操作覆盖了第一个,是因为两个图像的取值范围差异太大:
img1的取值范围是0-1img2的取值范围是0-9999
使用同一个rainbow颜色映射时,img1的所有值相对于img2的最大值来说几乎趋近于0,导致它在背景图里和全零背景的视觉差异极小,看起来像是被覆盖了。
解决方法一:归一化图像取值范围
将img2的数值缩放到和img1一致的0-1区间,这样两者在颜色映射下的视觉表现会匹配:
import numpy as np import matplotlib.pyplot as plt # 初始化数组 img1 = np.random.rand(400,400) img2 = np.arange(0,10000).reshape((100,100)) # 归一化img2到0-1区间 img2_normalized = img2 / img2.max() background = np.zeros(shape=(1600, 1600)) # 嵌入第一张图像 background[0:img1.shape[0], 0:img1.shape[1]] = img1 # 嵌入第二张归一化后的图像 background[500:500+img2.shape[0], 500:500+img2.shape[1]] = img2_normalized # 绘制结果 fig, ax = plt.subplots(3, 1, figsize=(5, 10)) ax[0].imshow(img1, cmap='rainbow') ax[0].set_title('原始img1') ax[1].imshow(img2_normalized, cmap='rainbow') ax[1].set_title('归一化后的img2') ax[2].imshow(background, cmap='rainbow') ax[2].set_title('同时包含两个图像的背景') plt.tight_layout() plt.show()
解决方法二:调整显示的颜色范围
不修改原始数组,在显示背景图时手动指定颜色映射的最小值和最大值,让两个图像的细节都能展现:
import numpy as np import matplotlib.pyplot as plt # 初始化数组 img1 = np.random.rand(400,400) img2 = np.arange(0,10000).reshape((100,100)) background = np.zeros(shape=(1600, 1600)) # 嵌入第一张图像 background[0:img1.shape[0], 0:img1.shape[1]] = img1 # 嵌入第二张图像 background[500:500+img2.shape[0], 500:500+img2.shape[1]] = img2 # 绘制结果 fig, ax = plt.subplots(3, 1, figsize=(5, 10)) ax[0].imshow(img1, cmap='rainbow') ax[0].set_title('原始img1') ax[1].imshow(img2, cmap='rainbow') ax[1].set_title('原始img2') # 指定vmin和vmax,覆盖整个数值范围 ax[2].imshow(background, cmap='rainbow', vmin=0, vmax=img2.max()) ax[2].set_title('同时包含两个图像的背景') plt.tight_layout() plt.show()
两种方法都能让你在背景图中同时看到两个嵌入的图像,选择哪种取决于你是否需要保留img2的原始数值。
内容的提问来源于stack exchange,提问作者john
相关产品推荐
相关产品推荐

