在 MATLAB 中將彩色影像的背景更改為灰度


我們可以透過將 RGB 值設定為 128 來獲得灰度顏色。這意味著所有顏色通道將具有相同的強度值。

以下 MATLAB 程式說明了將彩色影像的背景更改為灰度的程式碼。

示例

%MATLAB program to demonstrate changing color background into grayscale
% Read the input colored image
img1 = imread('https://tutorialspoint.tw/assets/questions/media/14304-1687425236.jpg'); 
% Display the input color image
subplot(1, 2, 1); imshow(img1); title('Original Image');
% Create a binary mask of the background
BGMask = img1(:, :, 1) == img1(1, 1, 1) & ...
                 img1(:, :, 2) == img1(1, 1, 2) & ...
                 img1(:, :, 3) == img1(1, 1, 3);
% Place the background pixels to black in the color image
img2 = img1;
img2(repmat(BGMask, [1, 1, 3])) = 0;
% Display the black background image
subplot(1, 2, 2); imshow(img2); title('Black BG Image');
    

輸出

注意 - 使用具有純色背景的影像以獲得所需的結果。

結論

在上述 MATLAB 程式中,我們使用“imread”函式讀取輸入的彩色影像,並使用“imshow”函式顯示原始影像。然後,我們建立影像背景的二值掩碼,在本例中,我們假設背景是純色,並從影像的左上角獲取樣本背景。之後,我們透過將 RGB 值設定為 128 來將彩色影像中的背景畫素設定為灰度。最後,我們使用“imshow”函式顯示具有灰度背景的影像“img2”。

更新於: 2023-07-18

75 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.