问题
I have an image of leaf that has mostly three colors black background, green leaf and brown diseased spots. Here is the image
When I cluster it first time, I get brown spots in cluster 1, green portion in cluster 2, black region in cluster 3(for example).
When I cluster it second time, I get green portion in cluster 1,brown spots in cluster 2, black region in cluster 3(for example). b
When I cluster it third time the order of clusters are different again.
I want to change the code such that the brown spots appear in cluster 1, green portion in cluster 2 and black in cluster 3. The order of clusters should be same even if I cluster many times.Could someone please help me with the code? I am using Matlab2009a. This question is about ordering clusters
Here is what is being done so far
function segmented_img = leaf_segmentation( original_img, nclusters )
original_img = im2double(original_img);
G=fspecial('gaussian',[200 250],1);
smoothed_img =imfilter(original_img,G,'same');
conversionform = makecform('srgb2lab');
lab_img = applycform(smoothed_img,conversionform);
ab_img = double(lab_img(:,:,2:3));
nrows = size(ab_img,1);
ncols = size(ab_img,2);
ab_img = reshape(ab_img,nrows*ncols,2);
cluster_idx =
kmeans(ab_img,nclusters,'distance','sqEuclidean','Replicates',3);
cluster_img = reshape(cluster_idx,nrows,ncols);
segmented_img = cell(1,nclusters);
for k = 1:nclusters
segmented_img{k} = bsxfun( @times, original_img, cluster_img == k );
end
end
segmented = leaf_segmentation( imread('input image'), 3 );
figure,imshow(segmented{1}), title('Cluster 1');
figure, imshow(segmented{2}), title('Cluster 2');
figure, imshow(segmented{3}), title('Cluster 3');
回答1:
Matlab kmeans has a 'Start' parameter, which can be set to a matrix of centroid initial locations. You can initialize to black, brown and green and you will probably even get the results a bit faster, if the image is really mostly composed of these colours.
Documentation
回答2:
Just check the colors after the clustering!
One way of doing this is transforming the centroids color space to HSV and checking the values oh H and V. H will give you the color (for example, around 120.0 degrees its green) and V will give you the "ligth", so if V is 0 then whatever H is, it is the black cluster.
This should be trivial to program, but dont hesitate to ask any questions about it.
来源:https://stackoverflow.com/questions/37959756/how-to-accurately-order-the-clusters-based-on-color-in-matlab