使用l * a * b(region_coordinates和samples)进行颜色分割(MATLAB)

时间:2016-01-08 10:27:18

标签: matlab colors image-segmentation

我想按颜色分割图片。我的示例图片是:

这是我第一次使用MATLAB。

首先,我只想检测"红色","绿色"和"蓝"。我不知何故让代码工作,它不仅检测红色,而是红色范围内的所有颜色。蓝色和绿色也一样。但我只需要红色,蓝色和绿色。

也许这段代码对我来说太过分了。可能有更好的解决方案。

其次,是否可以设置颜色样本并将此样本用于不同的图片。我不想一次又一次地为每张照片设置样本。

clear all
close all

fabric = imread('sam3.JPG');
figure(1), imshow(fabric), title('fabric');

%% Step 2: Calculate Sample Colors in L*a*b* Color Space for Each Region

在这里,我不知道如何获得坐标。我尝试使用此线程Colour Segmentation by l*a*b中提到的方法。但不知怎的,它不起作用。我绘制一个多边形并右键单击我可以复制它看起来像这样的位置:

[1082.5 730.5;1266.5 802.5;1186.5 962.5;1018.5 886.5] %section of red

所以我把它转换为红色

region_coordinates(:,1,1)=[1082.5 1266.5 1186.5 1018.5];
region_coordinates(:,2,1)=[730.5 802.5 962.5 886.5]; %red
region_coordinates(:,1,2)=[1602.5 1722.5 1622.5 1494.5];
region_coordinates(:,2,2)=[494.5 626.5 734.5 594.5]; %blue
region_coordinates(:,1,3)=[1794.5 1994.5 2014.5 1826.5];
region_coordinates(:,2,3)=[730.5 690.5 882.5 906.5]; %green
region_coordinates(:,1,4)=[2878.5 3078.5 3098.5 2910.5];
region_coordinates(:,2,4)=[1338.5 1298.5 1490.5 1514.5]; %black

其余代码来自LabColorSegementationExample

nColors = 4;
sample_regions = false([size(fabric,1) size(fabric,2) nColors]);

for count = 1:nColors
sample_regions(:,:,count) = roipoly(fabric,region_coordinates(:,1,count),...
                                  region_coordinates(:,2,count));
end

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

%%
% 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]);

for count = 1:nColors
color_markers(count,1) = mean2(a(sample_regions(:,:,count)));
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));

%% Step 3: Classify Each Pixel Using the Nearest Neighbor Rule
% Create an array that contains your color labels,
% i.e., 0 = background, 1 = red, 2 = green, 3 = purple, 4 = magenta, and 5 =     yellow.

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

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;

%% Step 4: Display Results of Nearest Neighbor Classification 
% The label matrix contains a color label for each pixel in the fabric
% image. Use the label matrix to separate objects in the original fabric
% image by color.

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 

imshow(segmented_images(:,:,:,2)), title('red objects');

%%

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

%%

imshow(segmented_images(:,:,:,8)), title('purple objects');

%%

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

%%

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


%% Step 5: Display 'a*' and 'b*' Values of the Labeled Colors.
% You can see how well the nearest neighbor classification separated the
% different color populations by plotting the 'a*' and 'b*' values of pixels     that 
% were classified into separate colors.  For display purposes, label each
% point with its color label.

purple = [119/255 73/255 152/255];
plot_labels = {'k', 'r', 'g', purple, 'm', 'y'};

figure
for count = 1:nColors
plot(a(label==count-1),b(label==count-1),'.','MarkerEdgeColor', ...
   plot_labels{count}, 'MarkerFaceColor', plot_labels{count});
hold on;
end

title('Scatterplot of the segmented pixels in ''a*b*'' space');
xlabel('''a*'' values');
ylabel('''b*'' values');


displayEndOfDemoMessage(mfilename)

1 个答案:

答案 0 :(得分:0)

我只是想发布代码,也许它会帮助一些人。 它可能不是最好的代码,但它可以工作。

如果我可以减少原始图像中的反射(可能使用偏振滤镜?)我会很高兴。或者我可以用代码删除反射?我尝试使用strel和imfill进行不同的变化并获得了很好的效果,但我无法消除反射。

%%
clc;
clear;
close all;
%% Read image
B=imread('sam3.JPG');
imghsv=imread('sam3.JPG');
imghsv=rgb2hsv(im2double(imghsv));
imshow(imghsv);
%% pick color
%red
redIndex=repmat((imghsv(:,:,1)>0/360)&(imghsv(:,:,1)<5/360),[1 1 3]);   
red=imghsv.*redIndex;
%green
greenIndex=repmat((imghsv(:,:,1)>150/360)&(imghsv(:,:,1)<165/360),[1 1 3]);   
green=imghsv.*greenIndex;
%blue
blueIndex=repmat((imghsv(:,:,1)>200/360)&(imghsv(:,:,1)<225/360),[1 1 3]);   
blue=imghsv.*blueIndex;
%% convert to binary image and fill in holes. Set level for binary image
% red
redBW = im2bw(red,0.01);
IfilledRed = imfill(redBW,'holes');
% blue
blueBW = im2bw(blue,0.51);
IfilledBlue = imfill(blueBW,'holes');
% green
greenBW = im2bw(green,0.31);
IfilledGreen = imfill(greenBW,'holes');
subplot(2,2,1), subimage(IfilledRed)
title('Red')  
axis('off')
subplot(2,2,2), subimage(IfilledBlue)
title('Blue')  
axis('off')
subplot(2,2,3), subimage(IfilledGreen)
title('Green')  
axis('off')
subplot(2,2,4), subimage(B)
title('Example')  
axis('off')
%% 
% red
seRed = strel('square', 22);
IopennedRed = imopen(IfilledRed,seRed);
imshow(IopennedRed);
% blue
seBlue = strel('square', 56);
IopennedBlue = imopen(IfilledBlue,seBlue);
imshow(IopennedBlue);
% green
seGreen = strel('square', 22);
IopennedGreen = imopen(IfilledGreen,seGreen);
imshow(IopennedGreen);
% compare
subplot(2,2,1), subimage(IopennedRed)
title('Red')  
axis('off')
subplot(2,2,2), subimage(IopennedBlue)
title('Blue')  
axis('off')
subplot(2,2,3), subimage(IopennedGreen)
title('Green')  
axis('off')
subplot(2,2,4), subimage(B)
title('Example')  
axis('off')
%% Initialize
% red
redObjectsMask = uint8(IopennedRed & IopennedRed & IopennedRed);
maskedrgbImageRed = uint8(zeros(size(IopennedRed))); 
% blue
blueObjectsMask = uint8(IopennedBlue & IopennedBlue & IopennedBlue);
maskedrgbImageBlue = uint8(zeros(size(IopennedBlue))); 
% green
greenObjectsMask = uint8(IopennedGreen & IopennedGreen & IopennedGreen);
maskedrgbImageGreen = uint8(zeros(size(IopennedGreen)));
%% combine RGB image and mask
% red
maskedrgbImageRed(:,:,1) = B(:,:,1) .* redObjectsMask;
maskedrgbImageRed(:,:,2) = B(:,:,2) .* redObjectsMask;
maskedrgbImageRed(:,:,3) = B(:,:,3) .* redObjectsMask;
% blue
maskedrgbImageBlue(:,:,1) = B(:,:,1) .* blueObjectsMask;
maskedrgbImageBlue(:,:,2) = B(:,:,2) .* blueObjectsMask;
maskedrgbImageBlue(:,:,3) = B(:,:,3) .* blueObjectsMask;
% green
maskedrgbImageGreen(:,:,1) = B(:,:,1) .* greenObjectsMask;
maskedrgbImageGreen(:,:,2) = B(:,:,2) .* greenObjectsMask;
maskedrgbImageGreen(:,:,3) = B(:,:,3) .* greenObjectsMask;
%%
%% Extract features
% red
IregionRed = regionprops(IopennedRed, 'centroid');
[labeledRed,numObjectsRed] = bwlabel(IopennedRed,4);
statsRed = regionprops(labeledRed,'Eccentricity','Area','BoundingBox');
areasRed = [statsRed.Area];
eccentricitiesRed = [statsRed.Eccentricity];
% blue
IregionBlue = regionprops(IopennedBlue, 'centroid');
[labeledBlue,numObjectsBlue] = bwlabel(IopennedBlue,4);
statsBlue = regionprops(labeledBlue,'Eccentricity','Area','BoundingBox');
areasBlue = [statsBlue.Area];
eccentricitiesBlue = [statsBlue.Eccentricity];
% green
IregionGreen = regionprops(IopennedGreen, 'centroid');
[labeledGreen,numObjectsGreen] = bwlabel(IopennedGreen,4);
statsGreen = regionprops(labeledGreen,'Eccentricity','Area','BoundingBox');
areasGreen = [statsGreen.Area];
eccentricitiesGreen = [statsGreen.Eccentricity];
%% Use feature analysis to count objects
% red
idxOfRed = find(eccentricitiesRed);
statsDefectsRed = statsRed(idxOfRed);

figure, imshow(maskedrgbImageRed);
hold on;
for idx = 1 : length(idxOfRed)
        hRed = rectangle('Position',statsDefectsRed(idx).BoundingBox,'LineWidth',2);
        set(hRed,'EdgeColor',[.75 0 0]);
        hold on;
end
if idx > 1
title(['There are ', num2str(numObjectsRed), ' detected areas in the image!']);
end
hold off;

% blue
idxOfBlue = find(eccentricitiesBlue);
statsDefectsBlue = statsBlue(idxOfBlue);

figure, imshow(maskedrgbImageBlue);
hold on;
for idx = 1 : length(idxOfBlue)
        hBlue = rectangle('Position',statsDefectsBlue(idx).BoundingBox,'LineWidth',2);
        set(hBlue,'EdgeColor',[.75 0 0]);
        hold on;
end
if idx > 1
title(['There are ', num2str(numObjectsBlue), ' detected areas in the image!']);
end
hold off;

% green
idxOfGreen = find(eccentricitiesGreen);
statsDefectsGreen = statsGreen(idxOfGreen);

figure, imshow(maskedrgbImageGreen);
hold on;
for idx = 1 : length(idxOfGreen)
        hGreen = rectangle('Position',statsDefectsGreen(idx).BoundingBox,'LineWidth',2);
        set(hGreen,'EdgeColor',[.75 0 0]);
        hold on;
end
if idx > 1
title(['There are ', num2str(numObjectsGreen), ' detected areas in the image!']);
end
hold off;
%%
subplot(2,2,1), subimage(maskedrgbImageRed)
title('Red')  
axis('off')
subplot(2,2,2), subimage(maskedrgbImageBlue)
title('Blue')  
axis('off')
subplot(2,2,3), subimage(maskedrgbImageGreen)
title('Green') 
axis('off')
subplot(2,2,4), subimage(B)
title('Example') 
axis('off')`