如何在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.tw/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程式碼將影像的綠屏背景更改為另一個背景。

更新於:2023年8月7日

262 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告