我想在baseImage(RGB图像)上放置一个modelImage(RGB图像),其中modelImage的中心将放置在pPoint。
我已经写了这个函数。
它有效。但是,modelImage中有一些0像素。我不想将0像素的modelImage放在baseImage上。你能帮我修改我的功能吗?
% Put the modelImage onto baseImage at pPoint
function newImage = imgTranslate(modelImage,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;
使用FOR和IF有效,但会减慢程序
%%
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
任何不使用FOR和IF的方法?
答案 0 :(得分:2)
可能有一种方法可以简化这一点,但有点像(未经测试):
% 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;
答案 1 :(得分:-1)
% 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;