且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与面具混合的图像

更新时间:2023-10-27 10:09:40

您的代码有两个问题。第一个问题是您尝试将颜色像素分配给输出图像 A ,但此图像仅为二维。您想要一个带有三个频道的图像,而不是两个。此外,您指定的输出图像类型是错误的。默认情况下,输出图像 A 的类型为 double ,但您正在将值复制到 aren 't double ...很可能是无符号的8位整数。

There are two problems with your code. The first problem is that you are trying to assign colour pixels to the output image A, yet this image is only two-dimensional. You want an image with three channels, not two. In addition, the output image type you are specifying is wrong. By default, the output image A is of type double, yet you are copying values into it that aren't double... most likely unsigned 8-bit integer.

因此,施法者图像与输入图像的类型相同。假设两个输入图像的类型相同,请初始化 A ,以便:

As such, cast the image to the same type as the input images. Assuming both input images are the same type, initialize your A so that:

A = zeros(size(foreground), class(foreground));

这正确地生成与任何输入相同类型的彩色图像,假设它们是两种都是相同的类型。

This correctly makes a colour image with the same type as any of the inputs, assuming that they're both the same type.

现在,你的 for 循环没问题,但如果你这样做的话会更好使用逻辑索引进行拍摄。如果您想使用逻辑索引,请创建一个最初为空的图像,就像您已完成的那样,但请确保您的模板有三个通道以匹配通道数其他图片有。之后,您只需索引每个图像并相应地设置正确的位置:

Now, your for loop is fine, but it's better if you do this in one shot with logical indexing. If you want to use logical indexing, create a new image that's initially blank like what you've done, but then make sure your mask has three channels to match the number of channels the other images have. After, you simply need to index into each image and set the right locations accordingly:

mask = imread('mask.png');
foreground = imread('fg.jpg');
background = imread('bg.jpg');
[r,c,d]=size(mask); %// Change

%// If your mask isn't three channels, make it so
%// Change
if d ~= 3
    mask = cat(3, mask, mask, mask);
end

A = zeros(size(foreground), class(foreground)); %// Change

A(mask) = foreground(mask); %// Assign pixels to foreground
A(~mask) = background(~mask); %// Assign pixels to background

imshow(A);