MATLAB: How to blend an image that is a non-rectangular mask with a background image

Image Processing Toolboximagesimmultiplyinfuse

Okay, I'm stumped.
I have a background image and I want to put a circular mask image on top of it, blended together 50-50 for everything within the circle. I want to stick with images and not use figures so that I can view the results with imagesc(image).
If pic1 is the full image that is cropped into the circle, and pC is a black circle on a white background with dimensions bCx, bCy, I use this to add in the image I want.
pzzc = imadd(pic1(bCx,bCy,:),pC);
I now have a circle with the original image in it and a white background. So far so good.
I now want to combine that image with the background image, such as this.
pzzz = imfuse(pzzz, pzzc,'blend');
The problem is that this doesn't work, as I can't get rid of the square bounding box around the circle image, since it's a mean of the 2 images, white and background.
immultiply doesn't work either. With this alternate approach:
pzz = immultiply(uint16(pzzz(bCx,bCy,:)), uint16(pzzc)); % IMAGE AND BACKGROUND
pzzz(bCx,bCy,:) = uint8(pzz);
pzz has the circle correct but is unblended, and the masked part of pzzz just comes out white.
If I have to I can live with the unblended image, but I don't understand why the masked part of the full image is white.
A full code example below:
clear all
pic1 = imread('visionteam.tif');
[x,y,z] = size(pic1);
pzzz = 20-uint8(zeros(x, y, z));
% ADD A DARK GRAY TO BACKGROUND IMAGE TO SEE IF CIRCLE LOSES BACKGROUND WHITE AREA
pC = imread('Circle1000x1000.tif'); % 1000 X 1000 BLACK CIRCLE WITH WHITE BACKGROUND
bbox = [86 52 70 70]; % X Y H W
pC = imresize(pC,[bbox(1,3), bbox(1,4)]); % RESIZE CIRCLE TO BB DIMENSIONS
bCx = bbox(1,1):bbox(1,1)+bbox(1,3)-1; % FIND X AND Y AREA OF BB
bCy = bbox(1,2):bbox(1,2)+bbox(1,3)-1;
mask = imadd(pic1(bCx,bCy,:),pC); % ADD Visionteam IMAGE INSIDE CIRCLE
mask = uint8(mask);
pzzz(bCx,bCy,:) = immultiply(uint16(pzzz(bCx,bCy,:)), uint16(mask))/255;
pzzz = uint8(pzzz);
imagesc(pzzz)

Best Answer

Please attach 'visionteam.tif' and 'Circle1000x1000.tif' or two similar images.
What I'd do is to make a mask and then convert to double, then add, and convert back to uint8. Untested code:
% Now sum with opacity factor
factor = 0.5;
sumImage = uint8(factor * double(backgroundImage) + (1 - factor) * teamImage);
% Mask the sum image using bsxfun() function to multiply the mask by each channel individually.
maskedTeamImage = bsxfun(@times, sumImage, cast(circleMask, 'like', sumImage));
% Burn a black circle into the background so we can add them there.
maskedBackgroundImage = bsxfun(@times, backgroundImage, cast(~circleMask, 'like', teamImage));
% Now simply sum them up to fill in the circle with the 50/50 blended circle patch.
outputImage = maskedBackgroundImage + maskedTeamImage; % Initialize