K.soula
K.soula

Reputation: 45

Split histogram into different regions in Matlab

I have an Image histogram using imhist and it contains 3 different regions like the attached image shows, I want to get the borders or the interval of the largest continuous area of the histogram, in this case, the second region is the one that I am looking for and the borders would be 43 and 225

the image histogram

Upvotes: 2

Views: 343

Answers (2)

DontCareBear
DontCareBear

Reputation: 834

I will use the answer to this question to find regions of consecutive non zero elements in an array.

lets assume we have this array (histogram):

h = [0,0,0,1,2,3,44,77,5,656,0,0,0,0,0,0,2,99,7,34];

now we want to know were each region of consecutive non-zero elements starts and ends, in this example we want

startIndex = [4,17]
endIndex   = [10,20]
lengths    = [7,4]

to get this result we use the code from the question as follows:

dsig = diff([1,h(:)'==0,1]);
startIndex = find(dsig < 0);
endIndex = find(dsig > 0)-1;
duration = endIndex-startIndex+1;

and to get longest region use:

[~,maxLengthIndex] = max(lengths);
maxStartIndex = startIndex(maxLengthIndex);
maxEndIndex = endIndex(maxLengthIndex);

Upvotes: 0

jodag
jodag

Reputation: 22194

You can find the begin and end bins for each region like this

[counts,binLocations] = imhist(I);
der = diff([false; counts>0; false]);
upedge = find(der == 1);
downedge = find(der == -1) - 1;
regions = [binLocations(upedge) binLocations(downedge)];

If the values are not exactly zero, but very close to zero then you can replace 0 with some threshold value in the above code.

Example

im = uint8(zeros(300,400));
im(1:100,:) = uint8(randi([0,40],[100,400]));
im(101:200,:) = uint8(randi([90,100],[100,400]));
im(201:300,:) = uint8(randi([140,240],[100,400]));

[counts,binLocations] = imhist(im);
der = diff([false; counts>0; false]);
upedge = find(der == 1);
downedge = find(der == -1) - 1;
regions = [binLocations(upedge) binLocations(downedge)];

results in

regions =

     0    40
    90   100
   140   240

Upvotes: 1

Related Questions