Azzera filtri
Azzera filtri

Copy part of an RGB image to another

7 visualizzazioni (ultimi 30 giorni)
youngz
youngz il 30 Lug 2019
Modificato: Guillaume il 30 Lug 2019
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

Risposta accettata

Guillaume
Guillaume il 30 Lug 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 Commenti
youngz
youngz il 30 Lug 2019
Modificato: youngz il 30 Lug 2019
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 il 30 Lug 2019
Modificato: Guillaume il 30 Lug 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;

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Image Processing Toolbox in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by