在 matlab / octave 中转换 RGB 和 HSV 值

converting RGB and HSV values in matlab / octave

我使用 rgb2hsv 创建了一个动画来查看 RGB 的不同值和等效的 HSV 值,但是 colors don't match at all 我是否使用了错误的转换? 我期望获得相似的颜色并获得与 RGB 值等效的 HSV 值,我该怎么做?

我用来测试的示例代码以及下面的动画。

clear all,clf reset,tic,clc
pkg load image
for ii=1:5:255
  ii;

  r(:,:,1)=127;
  g(:,:,1)=mod(19+ii,255);
  b(:,:,1)=12;
  rgb_img(:,:,1)=r;
  rgb_img(:,:,2)=g;
  rgb_img(:,:,3)=b;
  rgb_img=uint8(rgb_img); %convert so Imshow an show image

  hsv_img=rgb2hsv(rgb_img);
  h=hsv_img(:,:,1);
  s=hsv_img(:,:,2);
  v=hsv_img(:,:,3);
  hsv_img=uint8(hsv_img); %convert so Imshow an show image

  pause(.0001)

  height_wanted=300;%size(img,1) %length wanted needs to stay size(repmat_rgb,1) to get all colors. only change for testing
  width_wanted=280; %width wanted can be changed

  rgb_out = imresize(rgb_img, [height_wanted, width_wanted]); %reshape output
  hsv_out = imresize(hsv_img, [height_wanted, width_wanted]); %reshape output

  str_rgb1=('RGB Values');
  str_rgb2=(sprintf('\nRed=%3d  Green=%3d  Blue=%3d',r,g,b));
  str_hsv1=('HSV Values');
  str_hsv2=(sprintf('\nHue=%0.3f  Satuation=%0.3f  Value=%0.3f',h,s,v));

  subplot(1,2,1);imshow(rgb_out); title([str_rgb1,str_rgb2]);
  subplot(1,2,2);imshow(hsv_out); title([str_hsv1,str_hsv2]);
end

Ps:我使用的是 Octave 4.0,它类似于 Matlab

正如其他人在评论中提到的,您不能像显示任何其他图像一样显示 HSV 图像,因为它是一种根本不同的颜色表示。 3-D HSV 图像矩阵不会显示为任何特别有意义的图像显示函数在 MATLAB 中(如 imshow),因为它们会简单地将它们(错误地)解释为 RGB 图像(即色调通道被视为红色,饱和通道为绿色,值通道为蓝色。

您可能想要做的是分别显示每个 HSV 通道:

  • 色调作为 HSV color map 的索引。
  • 饱和度作为颜色存在量的灰度表示(0 = 灰度,1 = 纯色)。
  • 该值作为亮度的灰度表示(0 = 最暗,1 = 最亮)。

这里有一些代码可以生成与您的相似的图,但有 4 个图而不是 2 个(我相信这应该适用于 MATLAB 和 Octave):

rgb_img = zeros([300 300 3], 'uint8');
redValue = 127;
rgb_img(:, :, 1) = redValue;
blueValue = 12;
rgb_img(:, :, 3) = blueValue;
hsvMap = hsv(360);
figure('Position', [100 100 1000 500]);

for greenValue = 0:5:255
  rgb_img(:, :, 2) = greenValue;
  hsv_img = rgb2hsv(rgb_img);
  hsvIndex = round(hsv_img(:, :, 1).*359)+1;
  h_img = reshape(hsvMap(hsvIndex(:), :), [300 300 3]);

  subplot(1, 4, 1);
  imshow(rgb_img);
  title(sprintf('RGB = (%3d, %3d, %3d)', redValue, greenValue, blueValue));
  set(gca, 'Visible', 'on', 'Box', 'on', 'XTick', [], 'YTick', []);

  subplot(1, 4, 2);
  imshow(h_img);
  title(sprintf('Hue = %0.3f', hsv_img(1, 1, 1)));
  set(gca, 'Visible', 'on', 'Box', 'on', 'XTick', [], 'YTick', []);

  subplot(1, 4, 3);
  imshow(hsv_img(:, :, 2), []);
  title(sprintf('Saturation = %0.3f', hsv_img(1, 1, 2)));
  set(gca, 'Visible', 'on', 'Box', 'on', 'XTick', [], 'YTick', []);

  subplot(1, 4, 4);
  imshow(hsv_img(:, :, 3), []);
  title(sprintf('Value = %0.3f', hsv_img(1, 1, 3)));
  set(gca, 'Visible', 'on', 'Box', 'on', 'XTick', [], 'YTick', []);
  drawnow;
end

这是动画: