在 MATLAB 中将彩色图像的背景更改为灰度
我们可以通过将 RGB 值设置为 128 来获得灰度颜色。这意味着所有颜色通道将具有相同的强度值。
以下 MATLAB 程序说明了将彩色图像的背景更改为灰度的代码。
示例
%MATLAB program to demonstrate changing color background into grayscale % Read the input colored image img1 = imread('https://tutorialspoint.com/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”。
广告