如何在 MATLAB 中使用 HSV 色彩空间进行颜色切片?


在数字图像处理中,从图像中提取特定颜色或颜色范围并将所有其他颜色丢弃的过程称为颜色切片。在图像中,颜色切片是通过创建一个二值掩码来执行的,该掩码选择图像中位于指定颜色范围内的所有像素。

颜色切片通常用于特定的颜色空间,例如 RGB(红-绿-蓝)颜色空间或 HSV(色相-饱和度-值)颜色空间等。

在本文中,我们将学习**如何使用 MATLAB 编程在 HSV 色彩空间中执行颜色切片**。

在 HSV 色彩空间中,颜色切片是通过考虑图像的色相分量来执行的。其中,“色相”表示颜色色调。从 0 到 1 的范围表示 HSV 色彩空间中色相值的整个颜色光谱。

颜色切片广泛用于图像处理中,用于执行各种任务,例如去除背景、图像分割、目标识别等。

现在,让我们借助 MATLAB 示例程序了解 HSV 色彩空间中颜色切片的过程。

从红色到绿色对图像进行颜色切片

示例

% MATLAB program to perform color slicing to green using HSV color space
% Read the input image
in_img = imread('https://tutorialspoint.com/assets/questions/media/14304-1687425236.jpg');

% Convert the image from RGB format to HSV format
hsv = rgb2hsv(in_img);

% Extract the Hue channel of the HSV image
h = hsv(:, :, 1);

% Change all hue values within the red color range to green color
red_range = [0, 0.1]; % Red color range in HSV
h(h >= red_range(1) | h <= red_range(2)) = 0.3333; % Green color Hue value is 0.3333

% Replace the original Hue channel in the HSV image with the modified Hue channel
hsv(: , :, 1) = h;

% Convert the modified HSV image back to RGB image
out_img = hsv2rgb(hsv);

% Display the orignal image and the color-sliced image in green
figure;
subplot(1, 2, 1); imshow(in_img); title('Original Image');
subplot(1, 2, 2); imshow(out_img); title('Color Sliced to Green');

输出

代码说明

在此 MATLAB 代码中,我们首先使用“imread”函数读取 RGB 图像并将其存储在变量“in_img”中。接下来,我们使用“rgb2hsv”函数将输入图像从 RGB 色彩空间转换为 HSV 色彩空间,并将其存储在变量“hsv”中。然后,我们提取 HSV 图像的色相通道并将其存储在变量“h”中。

之后,我们在 HSV 色彩空间中指定红色范围“red_range”。然后,我们将此范围内的所有色相值设置为 0.3333,这是 HSV 空间中绿色的色相值。

接下来,我们用修改后的色相通道“h”替换 HSV 图像中的原始色相通道“hsv”以应用颜色切片。然后,我们使用“hsv2rgb”函数将修改后的 HSV 图像转换回 RGB 图像以获得颜色切片后的 RGB 图像,并将结果存储在变量“out_img”中。

最后,我们使用“imshow”函数显示原始图像和颜色切片为绿色的图像。

从红色到紫色对图像进行颜色切片

示例

% MATLAB program to perform color slicing using HSV color space
% Read the input image
in_img = imread('https://tutorialspoint.com/assets/questions/media/14304-1687425236.jpg');

% Convert the image from RGB format to HSV format
hsv = rgb2hsv(in_img);

% Extract the Hue channel of the HSV image
h = hsv(:, :, 1);

% Change all hue values within the red color range to violet color
red_range = [0, 0.1]; % Red color range in HSV
h(h >= red_range(1) | h <= red_range(2)) = 0.8; % Violet color code in HSV is 0.8

% Replace the original Hue channel in the HSV image with the modified Hue channel
hsv(:, :, 1) = h;

% Convert the modified HSV image back to RGB iimage
out_img = hsv2rgb(hsv);

% Display the orignal image and the color-sliced image in violet
figure;
subplot(1, 2, 1); imshow(in_img); title('Original Image');
subplot(1, 2, 2); imshow(out_img); title('Color Sliced to Violet');

输出

代码说明

在此 MATLAB 程序中,代码实现和执行与 MATLAB 程序(1)相同。唯一的区别是,在此 MATLAB 程序中,颜色切片是针对红色到紫色的颜色执行的,其中指定的紫色色相值为 HSV 色彩空间中的 0.8。

因此,在本文中,我们解释了使用 MATLAB 编程在 HSV 色彩空间中进行图像颜色切片。

更新于:2023年8月7日

264 次查看

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.