开发者

How to place an image A onto image B BUT I WANT TO IGNORE all O pixels of image A

开发者 https://www.devze.com 2023-03-17 10:34 出处:网络
I want to place a modelImage (RGB image) on baseImage (RGB image) where the center of modelImage will be placed at pPoint.

I want to place a modelImage (RGB image) on baseImage (RGB image) where the center of modelImage will be placed at pPoint.

I already wrote the function.

And it works. However, there are some 0 pixels in the modelImage. I do not want to place 0 pixels of modelImage onto baseImage. Can you help me to modify my function?

% Put the modelImage onto baseImage at pPoint
function newImage = imgTranslate(modelIm开发者_StackOverflow社区age,baseImage, pPoint)

[nRow nCol noDim] = size(modelImage);


pPointX = pPoint(1);
pPointY = pPoint(2);

startColumn = pPointY - nCol/2;
startRow = pPointX - nRow/2;

startColumn = round(startColumn);
startRow = round(startRow);

endColumn = startColumn+ nCol;
endRow = startRow+nRow;

%% Place modelImage onto baseImage BUT I WANT TO IGNORE O pixels of modelImage
baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:) = modelImage;
newImage = baseImage;

Using FOR and IF works but it will slow the progam

%%
for i = startRow: (endRow-1)
    x = (i-startRow +1);
    for j = startColumn : (endColumn-1)
         y = j-startColumn + 1;
        if modelImage(x,y,:)~=0
            baseImage(i,j,:) = modelImage(x,y,:);
        end
    end
end

Any way to not to use FOR and IF ?


There may be a way to simplify this, but something like (untested):

% Indicator map of non-zeros
nzs = any(modelImage,3);
nzs = repmat(nzs, [1 1 3]);

% Crop destination image
tmpImage = baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:);

% Replace all but non-zeros
tmpImage(nzs) = modelImage(nzs);

% Place into output image as before
baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:) = tmpImage;


% Indicator map of non-zeros
zs = modelImage(:,:,:)==0;
nzs = ~zs;

% Crop destination image
tmpImage = baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:);

% Replace all but non-zeros
tmpImage(nzs) = modelImage(nzs);

% Place into output image as before
baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:) = tmpImage;
0

精彩评论

暂无评论...
验证码 换一张
取 消