如何在Matlab中将前景图像放在背景图像上的指定位置?

时间:2014-12-08 19:58:01

标签: image matlab image-processing computer-vision foreground

我正在开展一项任务,其中我有一些像人类,玩具和食物这样的物体,它们是前景图像/物体,我有一个背景图像,例如。像一个公园。我需要将前景图像/对象放在背景图像上的指定位置。我正在使用Matlab。

我能够将前景图像放在背景图像上,但它位于中心 - 而不是指定的位置。 如何使用Matlab将前景图像放置在背景图像上的指定位置?

我的代码如下:

figure1 = figure;

ax1 = axes('Parent',figure1);
ax2 = axes('Parent',figure1);

set(ax1,'Visible','off');
set(ax2,'Visible','off');

[a,map,alpha] = imread('foreground.png');
I = imshow(a,'Parent',ax2);

set(I,'AlphaData',alpha);
imshow('Background.jpg','Parent',ax1);

我的图片:

1)我想要的是什么:

enter image description here

2)我得到了什么:

enter image description here

1 个答案:

答案 0 :(得分:1)

这是一个简单的解决方案,使用ginput,用户点击一个数字(这里只有一次),然后你获取点的坐标。在此示例中,有一个消息框要求用户选择一个点,然后在背景图像上绘制前景图像。请注意,在我的示例中,我将背景图像中的像素替换为前景像素。即我不使用alpha和透明度。希望对你没问题;如果没有,请告诉我。

在该示例中,我的“背景”图像是Matlab附带的辣椒图像,“前景”图像是也附带Matlab的梨图像。我使用一小部分图像进行演示。

以下是代码:

clear
clc
close all
%// Set up background image (peppers.png) and foreground image (part of
%// pears.png)
BackgroundImage = imread('peppers.png');

DummyForeground = imread('pears.png');
ForegroundImage = DummyForeground(50:200,50:200,:);

%// Get size of foreground image
[rowFore,colFore,channelFore] = size(ForegroundImage);

figure

imshow(BackgroundImage);

hMsg = msgbox('Select an anchor point for foreground image','modal');
uiwait(hMsg)

这看起来像这样:

enter image description here

%// Use ginput to prompt user to select a single point (i.e. the 1 in
%// brackets).
[x,y] = ginput(1);

调用ginput会产生以下结果:

enter image description here

 x = round(x);
 y = round(y);

%// Important!
hold on

%// Replace pixels of background image with foreground image. 
BackgroundImage(y:y+rowFore-1,x:x+colFore-1,:) = ForegroundImage;

imshow(BackgroundImage);

最后是带有前景图像的背景图像:

enter image description here

注意:看起来光标和放置的实际图像之间存在偏移;当我拍摄截图时发生的事情哈哈,这不是一个错误:)

现在,如果您想在前台添加许多图像,您可以使用多个点轻松修改代码以进行ginput调用,如下所示:

[x,y] = ginput %// Indefinite # of points)

or [x,y] = ginput(SomeNumber) %// Any number you want

并为您选择的每个点添加适当的图像。

希望这很清楚,它会让你开始!