Copy part of an RGB image to another

조회 수: 8 (최근 30일)
youngz
youngz 2019년 7월 30일
편집: Guillaume 2019년 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