Copy part of an RGB image to another

7 次查看(过去 30 天)
Hi,
I am looking for a method to copy part of an RGB image to another. The only way that I have found is to use a double for and copy pixel by pixel:
c1 = imread('car1.jpg');
c2 = imread('car2.jpg');
x = 500;
y = 700;
idx = zeros(size(c1,1),size(c1,2));
idx((y-200):(y+200),(x-300):(x+300)) = 1;
idx = logical(idx);
[row, col] = size(idx);
%Works but it is slow and ugly
for r = 1:row
for c = 1:col
if(idx(r,c))
rgb = c2(r,c,:);
c1(r,c,:) = rgb;
end
end
end
%c1(idx) = c2(idx); Not works
%c1(idx,:) = c2(idx,:); return error
imshow(c1);
Is there an elegant and faster way to implement it? Thanks

采纳的回答

Guillaume
Guillaume 2019-7-30
I really don't understand why you went with this very roundabout code, very little of it makes any sense:
e.g:
idx = zeros(size(c1,1),size(c2,2));
creates a vector with the same number of rows as c1 and the same numbers of columns as c2. Why the inconsistency?
Why create a logical array? Why iterate over all the rows and columns including the ones you don't want to copy when you already know the range you want to copy?
The whole thing can be simplified to:
c1(y-200:y+200, x-300:x+300, :) = c2(y-200:y+200, x-300:x+300, :);
  2 个评论
youngz
youngz 2019-7-30
编辑:youngz 2019-7-30
I recreate a small part of the program and the first part of data (i.e., c1, c2, and idx) are not data created by me, but they are variables that have been loaded.
For
idx = zeros(size(c1,1),size(c2,2));
it is my error. Anyway the two images have the same dimension..
Guillaume
Guillaume 2019-7-30
编辑:Guillaume 2019-7-30
Oh, ok. Then you should have made clear what you wanted us to start with. So, my understanding is that you have 3 arrays, c1 and c2 are 3D matrices of the same size representing images, and idx is a logical array indicating which pixels to copy. In that case:
rgbmask = repmat(idx, 1, 1, 3); %replicate pixel mask across all 3 colour channels
c2(rgbmask) = c1(rgbmask); %copy pixels indicated by the mask
---
Note: constructing your idx could have been done more simply with:
idx = false(size(c1, 1), size(c1, 2));
idx(y-200:y+200, x-300:x+300) = true;

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Image Processing Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by