Q: Merging neighboring connected components with different labels Consider the following image: 

On the left, let's say I have 3 labels. The background = 1, the black = 2, the orange = 3. What I want to do is be able to first identify all connected components that are orange, then if there are black objects touching the orange, then I'd like to convert this to orange as well. 
I know the following steps:


*

*Assume the labeled image is called labeled. I do orange = labeled == 3

*CC = bwconncomp(orange);
But from here, I'm not sure how I can check if any of the black components are touching the orange. Once I know which black components are touching the orange, I can do the following: RP = regionprops(black, 'PixelIdxList'); labeled(RP(index).PixelIdxList) = 3;
To test code: here is an example input and output generation:
%input matrix
I = zeros([8 8]);
I(1:5, 1:5) = 1;
I(2:4, 3:7) = 2;
I(7:8, 1:2) = 1;
I(7:8, 7:8) = 2;
I

%output
O = zeros([8 8]);
O(1:5, 1:5) = 1;
O(2:4, 3:7) = 1;
O(7:8, 1:2) = 1;
O(7:8, 7:8) = 2;
O


A: You can do it as follows. Let target denote the target value, corresponding to orange.


*

*Identify regions defined as connected components without regard to color, using bwlabel.

*For each region, if it contains at least a pixel equal to target, set the whole region to target.




target = 1; % value corresponding to orange
O = I;
[regions, numRegions] = bwlabel(I);
for regionId = 1:numRegions
    ind = regions==regionId;
    if any(I(ind)==target)
        O(ind) = target;
    end
end


A: This can be quite simply solved using imreconstruct. This function, for binary (logical) inputs, does a flood fill. The idea is to find an mask image (the orange and the black regions together) and a marker (or seed) image (the orange regions).
As a demo, let's start with what OP already has:
orig = readim('https://i.stack.imgur.com/rH7yT.png');
labeled = uint8(round((255-orig{2}(0:866,:))/127));
orange = labeled==1;  % for OP this is 3
black = labeled==2;   % for OP this is 2 also

(Note that labeled is not identical to the one that OP has, the numbers for each label are different.)
Now we can apply imreconstruct:
black_or_orange = orange | black;
output = imreconstruct(orange,black_or_orange);

output now contains the orange regions, grown to encompass any touching black regions. We can create a new labeled image as follows:
new_labeled = uint8(output) + 2*uint8(black & ~output);


