如何生成两张同像素尺寸RGB图像的差值(Delta)图?
图像差值可视化需求与实现过程
我有两张RGB图像,用于表示某几何结构上标量变量的分布图。目标是绘制这两个图像间变量的差值,并使用自定义色图进行着色。
我已完成将图像转换为灰度图的步骤,但不清楚如何正确映射差值数组中的正负值。
初始尝试代码
import numpy as np import matplotlib as mpl from PIL import Image, ImageChops img1 = Image.open('img1.png').convert('L') img2 = Image.open('img2.png').convert('L') cm = mpl.colormaps['bwr'] img1_array = np.asarray(img1) img2_array = np.asarray(img2) diff_img = img1_array - img2_array im = cm(diff_img) im = np.uint8(im * 255) im = Image.fromarray(im).save("test_diff.png")
初始效果(不符合预期)

原始图像
图像1:
图像2:
编辑1:测试Martin建议后的实现代码
测试了Martin的建议,使用以下代码得到对应结果:
from PIL import Image, ImageChops import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # 打开图像 img1 = Image.open('img1.png').convert('L') img2 = Image.open('img2.png').convert('L') w,h = img1.width, img1.height arr1 = np.array(img1) arr2 = np.array(img2) im = (arr2 - arr1) im_min = im.min() im_max = im.max() im = np.uint8(128+(im-im_min)*255/(im_max-im_min)) figure, axes = plt.subplots(1,1) img = axes.imshow(np.array(im)) img.set_cmap('bwr') axes.patch.set_linewidth(1) axes.patch.set_edgecolor('k') axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) figure.colorbar(img, ax=axes, shrink=0.25, orientation="horizontal", pad=0.01) figure.set_size_inches(w/150,h/150) figure.tight_layout() figure.savefig('foo.png', dpi=150, bbox_inches='tight')
编辑2:加入标量映射后的优化代码
from PIL import Image, ImageChops import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import cv2 as cv from scipy.interpolate import interp1d # 打开图像 img1 = Image.open('test_1.png').convert('L') img2 = Image.open('test_2.png').convert('L') #img1.save('test_L.png') #img2.save('test_L.png') w,h = img1.width, img1.height arr1 = np.asarray(img1) arr2 = np.asarray(img2) diff = arr1 - arr2 m = interp1d([0,255],[-3, 1]) arr1_m = [] arr2_m = [] for n, val in enumerate(arr1): arr1_m.append((m(val)).tolist()) arr1_m = np.array(arr1_m) for n, val in enumerate(arr2): arr2_m.append((m(val)).tolist()) arr2_m = np.array(arr2_m) diff = arr2_m - arr1_m figure, axes = plt.subplots(1, 1) normalize = mpl.colors.Normalize(vmin=-0.5, vmax=0.5) img = axes.imshow(np.array(diff), norm=normalize) img.set_cmap('bwr') axes.patch.set_linewidth(1) axes.patch.set_edgecolor('k') axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) figure.colorbar(img, ax=axes, shrink=0.25, orientation="horizontal", pad=0.01) figure.set_size_inches(w/150,h/150) figure.tight_layout() figure.savefig('foo.png', dpi=150, bbox_inches='tight')
编辑2的最终效果

内容的提问来源于stack exchange,提问作者alie89
相关产品推荐
相关产品推荐

