如何在MATLAB中更改具有绿屏背景的图像的背景?
在这篇文章中,我们将学习如何使用MATLAB编程将图像的绿色背景更改为其他背景。
将绿屏背景更改为其他背景的概念涉及一项名为“色度键”的技术。这项技术检测图像中的绝对绿色,并将其从图像中去除。然后,我们可以将另一个图像或颜色作为图像的背景应用。
算法
下面解释了在MATLAB中使用另一个背景更改图像绿屏背景的分步过程
步骤(1) - 读取具有绿屏背景的输入图像。
步骤(2) - 读取要插入图像中作为绿屏替代背景的新背景图像。
步骤(3) - 根据需要将输入图像转换为RGB格式。
步骤(4) - 从图像中去除绿屏背景。
步骤(5) - 设置新的背景图像。
步骤(6) - 显示最终结果图像。
现在,让我们了解一下这些六个步骤在MATLAB编程中的实现和执行。
示例
% MATLAB Code for changing green screen background in an image
% Read the input image with green screen background
in_img = imread('https://ak.picdn.net/shutterstock/videos/2322320/thumb/1.jpg');
% Read the new background image
bg_img = imread('https://tutorialspoint.com/assets/questions/media/14304-1687425323.jpg');
% Convert the images into the RGB format with double precision for calculations
in_img = im2double(in_img);
bg_img = im2double(bg_img);
% Resize the new background image to match the size of the input image
bg_img = imresize(bg_img, [size(in_img, 1), size(in_img, 2)]);
% Remove the green screen background from the input image
x = 0.65; % Adjust the value based on your image’s requirements
a = in_img(:, :, 2); % Specify the green channel of the image
m = a > x;
% Change the green screen background with the new background image
out_img = in_img;
out_img(repmat(m, [1, 1, 3])) = bg_img(repmat(m, [1, 1, 3]));
% Display the original image, background image, and the output image
subplot(1, 3, 1); imshow(in_img); title('Original Image');
subplot(1, 3, 2); imshow(bg_img); title('New Background Image');
subplot(1, 3, 3); imshow(out_img); title('Output Image');
输出
代码解释
在这个MATLAB代码中,我们首先使用‘imread’函数读取绿屏输入图像和新的背景图像,并将它们分别存储在变量‘in_img’和‘bg_img’中。然后,我们使用‘im2double’函数将这两个图像转换为双精度RGB格式,以便进行更好的计算。然后,我们将背景图像的大小调整为与绿屏图像的大小匹配。
之后,我们从输入图像中去除绿屏背景。为此,我们定义一个阈值‘x’来确定我们要从图像中去除的绿色像素,您应该根据您的图像调整此值。
接下来,我们使用公式‘in_img(:, :, 2)’提取绿屏图像的绿色通道‘a’,并创建一个二进制掩码‘m’。在这个二进制掩码中,当绿色通道‘a’的值大于阈值‘x’时,每个像素的值设置为1。
之后,我们将‘in_img’的绿屏背景替换为背景图像‘bg_img’。为了执行此替换,我们使用‘repmat’函数。结果然后存储在变量‘out_img’中。
最后,我们调用‘imshow’函数来显示绿屏图像、背景图像和输出图像。
因此,在这篇文章中,我们解释了如何使用MATLAB代码将图像的绿屏背景更改为另一个背景。
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP