Copy part of an RGB image to another
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Guillaume
le 30 Juil 2019
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 commentaires
Guillaume
le 30 Juil 2019
Modifié(e) : Guillaume
le 30 Juil 2019
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;
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Image Processing Toolbox dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!