在Matlab中手动将RGB转换为HSV时出现怪异现象 [英] Weird phenomenon when converting RGB to HSV manually in Matlab
问题描述
我编写了一个小的Matlab函数,该函数使用RGB图像,并根据找到的转换公式将其转换为HSV 此处.
I have written a small Matlab funcion which takes an image in RGB and converts it to HSV according to the conversion formulas found here.
问题是,当我将其应用于色谱时,色谱中有一个割线,并且某些值是错误的,请参见图像(为了使比较容易,我已使用内部的hsv2rgb()
函数将其转换回RGB Matlabs自己的函数rgb2hsv()
不会发生这种情况,但是我找不到我做错了什么.
The problem is that when I apply this to a color spectrum there is a cut in the spectrum and some values are wrong, see images (to make the comparison easier I have used the internal hsv2rgb()
function to convert back to RGB. This does not happen with Matlabs own function rgb2hsv()
but I can not find what I have done wrong.
这是我的职责
function [ I_HSV ] = RGB2HSV( I_RGB )
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
[MAX, ind] = max(I_RGB,[],3);
if max(max(MAX)) > 1
I_r = I_RGB(:,:,1)/255;
I_g = I_RGB(:,:,2)/255;
I_b = I_RGB(:,:,3)/255;
MAX = max(cat(3,I_r, I_g, I_b),[],3);
else
I_r = I_RGB(:,:,1);
I_g = I_RGB(:,:,2);
I_b = I_RGB(:,:,3);
end
MIN = min(cat(3,I_r, I_g, I_b),[],3);
d = MAX - MIN;
I_V = MAX;
I_S = (MAX - MIN) ./ MAX;
I_H = zeros(size(I_V));
a = 1/6*mod(((I_g - I_b) ./ d),1);
b = 1/6*(I_b - I_r) ./ d + 1/3;
c = 1/6*(I_r - I_g) ./ d + 2/3;
H = cat(3, a, b, c);
for m=1:size(H,1);
for n=1:size(H,2);
if d(m,n) == 0
I_H(m,n) = 0;
else
I_H(m,n) = H(m,n,ind(m,n));
end
end
end
I_HSV = cat(3,I_H,I_S,I_V);
end
原始光谱 转换后的光谱
Original spectrum Converted spectrum
推荐答案
错误在于我简化了a
,b
和c
的计算.将其更改为以下内容可以解决该问题.
The error was in my simplification of the calculations of a
, b
, and c
. Changing it to the following solved the problem.
function [ I_HSV ] = RGB2HSV( I_RGB )
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
[MAX, ind] = max(I_RGB,[],3);
if max(max(MAX)) > 1
I_r = I_RGB(:,:,1)/255;
I_g = I_RGB(:,:,2)/255;
I_b = I_RGB(:,:,3)/255;
MAX = max(cat(3,I_r, I_g, I_b),[],3);
else
I_r = I_RGB(:,:,1);
I_g = I_RGB(:,:,2);
I_b = I_RGB(:,:,3);
end
MIN = min(cat(3,I_r, I_g, I_b),[],3);
D = MAX - MIN;
I_V = MAX;
I_S = D ./ MAX;
I_H = zeros(size(I_V));
a = 1/6*mod(((I_g - I_b) ./ D),6);
b = 1/6*((I_b - I_r) ./ D + 2);
c = 1/6*((I_r - I_g) ./ D + 4);
H = cat(3, a, b, c);
for m=1:size(H,1);
for n=1:size(H,2);
if D(m,n) == 0
I_H(m,n) = 0;
else
I_H(m,n) = H(m,n,ind(m,n));
end
if MAX(m,n) == 0
S(m,n) = 0;
end
end
end
I_HSV = cat(3,I_H,I_S,I_V);
end
这篇关于在Matlab中手动将RGB转换为HSV时出现怪异现象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!