Copy part of an RGB image to another
조회 수: 8 (최근 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
댓글 수: 0
채택된 답변
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
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 Center 및 File Exchange에서 Image Processing Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!