编辑:很抱歉昨天误解了你的问题,所以这是你的全彩版本:P
基本思想几乎相同MATLAB:组合两个具有不同 Alpha 的灰度图像,但就您而言,需要更多的操作才能获得正确的东西。
首先,使用提供的示例重新创建您所描述的情况
% load foreground image, and scale to [-50, 300]
Foreground = imread('500x_54.jpg');
figure(1)
imshow(Foreground)
Foreground = im2double(Foreground)*350-50;
% load background image
Background = im2double(imread('2-effect1-500x225.jpg'));
figure(2)
imshow(Background)
然后从头开始制作一个 Alpha 通道。请注意,我没有使用imagesc
但编写一个普通的双精度数组。这确实是一个 Alpha 通道!不需要那么多谜团。
% build alpha layer for Foreground
alpha = bsxfun(@times, ones(size(Foreground,1), size(Foreground,2)), .6);
alpha(:,[1:53,149:203,290:352,447:end])=0;
alpha([1:58,170:end],:)=0;
figure(3)
imshow(alpha)
在混合之前,我想将前景“向后”缩放为[0,1]
。由于背景图像是从常规图片中新鲜加载的,因此不需要标准化;只有 -50 到 300 范围内的前景可以。
问题是有时你有疯狂的数据,比如-100
or 1000
。我不知道你想如何解释它们。如果你采取[-50. 300]
作为常规的、典型的、应该的范围,那么你如何映射-100
or 1000
进入颜色级别?
有 2 个选项/方法可以处理这种情况: 1) 使用[-100, 1000]
作为一个新的尺度。所以-100
将是纯黑色并且1000
颜色纯正; 2)继续使用[-50, 300]
作为比例范围,因此超出该范围的所有内容都将被映射(强制)到最近的边界。
这里我选择第一个,有自适应机制,至少限制范围[-50, 300]
。所以如果你的数据像[-10,200]
,你仍然得到了规模[-50, 300]
。我认为这更有意义。
% find a scale dynamically with some limit
Foreground_min = min( min(Foreground(:)), -50 );
Foreground_max = max( max(Foreground(:)), 300 );
混合过程与那篇文章几乎相同。但您使用的是 RGB 图像,因此您需要add
所有 3 个颜色层的编号;bsxfun用于替换较慢的+
and .*
运营。
% overlay the image by blending
Background_blending = bsxfun(@times, Background, bsxfun(@minus,1,alpha));
% Background_blending = Background.*repmat((1-alpha), 1, 1, 3);
Foreground_blending = bsxfun( @times, bsxfun( @rdivide, ...
bsxfun(@minus, Foreground, Foreground_min), ...
Foreground_max-Foreground_min ), alpha );
% Foreground_blending = (Foreground-Foreground_min) / ...
% (Foreground_max-Foreground_min).*repmat(alpha, 1, 1, 3);
% out = bsxfun(@plus, Background_blending, Foreground_blending);
out = Background_blending + Foreground_blending;
figure(4)
imshow(out)
除第一行之外的注释行是“常规”分配命令而不使用bsxfun
,但做同样的工作,并且更容易理解:)
Result