在 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”。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP