Home > database >  Why is my HSV space segmentation in MATLAB not working?
Why is my HSV space segmentation in MATLAB not working?

Time:02-14

I am attending a class on image processing with Matlab and I found a problem on the internet and I tried to solve it but it is hard, because I am new to this subject.

The problem has to be solved with Matlab and it is new for me as well.

Problem:

'Think of RGB and HSV spaces as 3-dimensional spaces. Define a neighborhood distance (we can use ecludien distance) and set to 0 all the pixels whose value in RGB or HSV space is far (in the sense of this distance) from your reference value. See if you can easily achieve the same type of segmentation in both cases. Try for example to segment only the helmets of the warriors of the image bilibinWar.jpg.'

enter image description here

I tried to code it but it doesn't work.

clear all; close all;
ImagebilibinWar = imread("bilibinWar.jpg");
[lin, col, pla] = size(ImagebilibinWar);
figure;imshow(ImagebilibinWar);
ImagebilibinWarHSV= rgb2hsv(ImagebilibinWar);
[lo,co] = ginput(1);
lo = round(lo);
co = round(co);
RIOH = ImagebilibinWarHSV(lo,co,1)
RIOS = ImagebilibinWarHSV(lo,co,2)
RIOV = ImagebilibinWarHSV(lo,co,3)
%reference value that i have to choose
for a=0:0.05:1
    for i= 1:lin
        for j = 1:col
            d(i,j,:) = ((ImagebilibinWarHSV(i,j,1)-RIOH)^2   (ImagebilibinWarHSV(i,j,2)-RIOS)^2 (ImagebilibinWarHSV(i,j,3)-RIOV)^2)^0.5;
            if d(i,j,:) < a
                ImagebilibinWarHSV(i,j,:) = 0;
            end
        end
    end
    ImagebilibinWarRGB = hsv2rgb(ImagebilibinWarHSV);
    figure;imshow(ImagebilibinWarRGB);
end

So can some one help me with it? I do not get it.
I know that I have to get the number of line a column of a certain pixel using input and then do for loops for each line and column and then calculate the Euclidean distance. But I do not get it. I am kind of stuck.

CodePudding user response:

I don't think there is anything wrong with your code. The answer is that segmenting using euclidean distance in colors simply does not work for RGB or HSV spaces. The entire purpose of the L*a*b color space was indeed this, creating a color space where similar colors would have the little euclidean distance.

Here a less cluttered version of it:

clear all; close all;
ImagebilibinWar = imread("https://i.stack.imgur.com/wnBDu.jpg");
[lin, col, pla] = size(ImagebilibinWar);
figure;imshow(ImagebilibinWar);
ImagebilibinWarHSV= rgb2hsv(ImagebilibinWar);
[lo,co] = ginput(1);
lo = round(lo);
co = round(co);
RIOH = ImagebilibinWarHSV(lo,co,1);
RIOS = ImagebilibinWarHSV(lo,co,2);
RIOV = ImagebilibinWarHSV(lo,co,3);
%reference value that i have to choose
for a=0:0.05:1

    d = ((ImagebilibinWarHSV(:,:,1)-RIOH).^2   (ImagebilibinWarHSV(:,:,2)-RIOS).^2 (ImagebilibinWarHSV(:,:,3)-RIOV).^2).^0.5;

    ImagebilibinWarRGB = hsv2rgb(ImagebilibinWarHSV.*double(d<a));
    figure;imshow(ImagebilibinWarRGB);
end
  • Related