MATLAB: Grouping of similar pixels

image processingImage Processing ToolboxMATLAB

Is there any existing function that: 1. groups pixels with similar value together 2. finds the main axis orientation of the region ?

Best Answer

region_minsize = 5; %for example
uvals = unique(YourArray(:));
accumulated_list = struct('label', {}, 'props', {});
for K = 1 : length(uvals)
U = uvals(K);
accumulated_list(K).label = U;
BW = YourArray == U;
BW2 = bwareafilt(BW, [region_minsize, inf]); %discard areas that are too small
theseprops = regionprops(BW2, 'PixelList', 'Orientation');
accumulated_list(K).props = theseprops;
end
The result of this would be a structure array, one element per unique pixel value. The 'label' subfield will hold the value of the pixel being considered (in case you want to know.) The 'props' subfield will hold whatever is returned by regionprops(). regionprops returns a structure array with one field for each requested property, with one array element for each connected component. I made the assumption here that you want to (for example) consider the group of 3's in the top left as being distinct from the group in the bottom right. I also made the assumption that you probably want to know something about where the pixels are in addition to knowing the orientation. It would not surprise me if you want to add the MajorAxisLength property to the regionprops call.
bwareafilt is a relatively new routine for filtering by region size. I assumed here that you don't care about the orientation about the small groups, such as the isolated pixels, that there is a minimum size grouping that you wish to consider. If your Image Processing toolbox is not new enough to have bwareafilt() you can instead pass the unfiltered binary array in to regionprops and ask for the Area parameter as well, and then discard the elements that do not meet your specifications. For example,
theseprops = theseprops([theseprops.Area] >= 5);
Related Question