# Find consecutive numbers below threshold using bwlabel

3 views (last 30 days)
Konvictus177 on 1 Jun 2022
Commented: Konvictus177 on 3 Jun 2022
Hi,
I want to find all consecutive values and their region in a vector that are below a certain threshold.
I am able to do this using the following code. In this example I find 5 regions below the set threshold which is correct.
y = [1 2 1 2 3 4 5 4 3 2 0.4 0.3 0.4 0.4 0.6 0.4 0.5 0.4 0.6 0.5 0.3 0.5 0.6 0.2 1 2 3 4 1 2 3 2 3 2 5 4]
plot(y)
lowThreshold = 0.5
% label points below threshold as 1
[L, count] = bwlabel(y < lowThreshold); % label waves below threshold
% Get lengths of each region
props = regionprops(L, 'Area', 'PixelList');
regionLengths = [props.Area];
for k = 1 : count
fprintf('Region #%d is %d elements long and starts at element #%d\n',...
k, regionLengths(k), props(k).PixelList(1,1));
end
Now I want to modify this code to count the 5 regions as 1 connected big region although I exceed my threshold by a tiny amount. How can I do this? Take first index of region 1 and last index of region 5 and count as 1 large region. For example:
Thanks.

Steve Eddins on 2 Jun 2022
You could a hysteresis thresholding technique. First, threshold with a strict threshold, like your 0.5. Then, threshold with a slightly looser threshold, perhaps 0.1. Next, allow the strict threshold result to grow into adjacent regions that are included in the looser threshold result. The Image Processing Toolbox function imreconstruct can be used to do this. Here's a modified version of your code:
y = [1 2 1 2 3 4 5 4 3 2 0.4 0.3 0.4 0.4 0.6 0.4 0.5 0.4 ...
0.6 0.5 0.3 0.5 0.6 0.2 1 2 3 4 1 2 3 2 3 2 5 4];
plot(y)
lowThreshold = 0.5;
medThreshold = 0.7;
% Get lengths of each region.
% Note that regionprops can take a binary mask directly as input.
regionLengths = [props.Area];
for k = 1 : numel(props)
fprintf('Region #%d is %d elements long and starts at element #%d\n',...
k, regionLengths(k), props(k).PixelList(1,1));
hold on
[r1,r2] = bounds(props(k).PixelList(:,1));
plot([r1 r2],[0.5 0.5],'Color','r','Linewidth',3)
hold off
end
Region #1 is 14 elements long and starts at element #11
Konvictus177 on 3 Jun 2022
Wow, exactly what I was looking for. Love the solution so far.
I will test it a bit more and come back in case of any issues.
Thank you!

### Categories

Find more on Get Started with Image Processing Toolbox in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!