Цветовая сегментация по l*a*b

Я использую код на веб-сайте MatLab «Сегментация на основе цвета с использованием цветового пространства Lab*»: http://www.mathworks.com/help/images/examples/color-based-segmentation-using-the-lab-color-space.html

Итак, я пытаюсь выбрать некоторые области самостоятельно вместо использования «загрузить регион_координаты», используя roipoly (ткань), но я застреваю. Как сохранить координаты только что нарисованного многоугольника? На самом деле я следую совету lennon310 в Решении II, внизу страницы: Несколько вопросов о цветовой сегментации с L*a*b*

Я не знаю, когда сохранять region_coordinates и делать size(region_coordinates,1)

Я внес следующие изменения (Шаг 1):

1) Убрано "загрузить регион_координаты"

2) Добавлено "region_coordinates = roipoly(ткань);"

Вот код:

` %% Шаг 1

fabric = imread(file);

figure(1);                                                                   %Create figure window. "If h is not the handle and is not the Number property value of an existing figure, but is an integer, then figure(h) creates a figure object and assigns its Number property the value h."
imshow(fabric)
title('fabric')



%load regioncoordinates; % 6 marices(?) labelled val(:,:,1-6), 5x2 (row x column)
region_coordinates = roipoly(fabric);

nColors = 6;
sample_regions = false([size(fabric,1) size(fabric,2) nColors]); %Initializing an Image Dimension, 3x3 (:,:,:) to zero? Zeros() for arrays only I guess.
                        %Size one is column, size two is row?
for count = 1:nColors
  sample_regions(:,:,count) = roipoly(fabric,region_coordinates(:,1,count),region_coordinates(:,2,count));

end

figure, imshow(sample_regions(:,:,2)),title('sample region for red'); 

%%Шаг 2

% Convert your fabric RGB image into an L*a*b* image using rgb2lab .

lab_fabric = rgb2lab(fabric);


%Calculate the mean a* and b* value for each area that you extracted with roipoly. These values serve as your color markers in a*b* space.

a = lab_fabric(:,:,2);
b = lab_fabric(:,:,3);
color_markers = zeros([nColors, 2]);%... I think this is initializing a 6x2 blank(0) array for colour storage. 6 for colours, 2 for a&b colourspace.

for count = 1:nColors
  color_markers(count,1) = mean2(a(sample_regions(:,:,count))); %Label for repmat, Marker for 
  color_markers(count,2) = mean2(b(sample_regions(:,:,count)));
end

%For example, the average color of the red sample region in a*b* space is

fprintf('[%0.3f,%0.3f] \n',color_markers(2,1),color_markers(2,2));

%% Шаг 3: классифицируйте каждый пиксель, используя правило ближайшего соседа %

color_labels = 0:nColors-1;

% Initialize matrices to be used in the nearest neighbor classification.

a = double(a);
b = double(b);
distance = zeros([size(a), nColors]); 


%Perform classification, Elucidean Distance.

for count = 1:nColors
  distance(:,:,count) = ( (a - color_markers(count,1)).^2 + (b - color_markers(count,2)).^2 ).^0.5;
end

[~, label] = min(distance,[],3);
label = color_labels(label);
clear distance;

%% Шаг 4: Отображение результатов классификации ближайших соседей % % Матрица меток содержит цветовую метку для каждого пикселя изображения ткани. % Используйте матрицу этикеток для разделения объектов на исходном изображении ткани по цвету.

rgb_label = repmat(label,[1 1 3]);
segmented_images = zeros([size(fabric), nColors],'uint8');

for count = 1:nColors
  color = fabric;
  color(rgb_label ~= color_labels(count)) = 0;
  segmented_images(:,:,:,count) = color;
end

%figure, imshow(segmented_images(:,:,:,1)), title('Background of Fabric');
%Looks different somehow.
figure, imshow(segmented_images(:,:,:,2)), title('red objects');

figure, imshow(segmented_images(:,:,:,3)), title('green objects');

figure, imshow(segmented_images(:,:,:,4)), title('purple objects');

figure, imshow(segmented_images(:,:,:,5)), title('magenta objects');

figure, imshow(segmented_images(:,:,:,6)), title('yellow objects');



`

person Keyes34    schedule 13.01.2015    source источник


Ответы (1)


Вы можете получить координаты многоугольника, используя выходные аргументы в вызове roipoly. Затем вы можете получить бинарную маску многоугольника, а также координаты вершин, если хотите.

Простой пример, демонстрирующий:

clear
clc
close all

A = imread('cameraman.tif');

figure;
imshow(A)

%// The vertices of the polygon are stored in xi and yi;
%// PolyMask is a binary image where pixels == 1 are white.
[polyMask, xi, yi] = roipoly(A);

Это выглядит так:

введите здесь описание изображения

И если вы хотите увидеть вершины с бинарной маской:

%// display polymask
imshow(polyMask)
hold on

%// Highlight vertices in red
scatter(xi,yi,60,'r')
hold off

Что дает следующее:

введите здесь описание изображения

Итак, подведем итог:

1) Вершины многоугольника хранятся в xi и yi.

2) Вы можете построить бинарную маску многоугольника, используя imshow(polyMask).

3) Если вам нужны координаты белых пикселей, вы можете использовать что-то вроде этого:

[row_white,col_white] = find(polyMask == 1);

Тогда вы можете идти. Надеюсь, это поможет!

person Benoit_11    schedule 13.01.2015