- Suppose you have an image,
- Now you want to shift those pixels to ....??? what happen on present pixels location?
- When the pixel shift to other location, is it oerwrite on present pixels?
- Location: source and destination pixels location?
Shifting pixels in an image without loops
조회 수: 23 (최근 30일)
이전 댓글 표시
Hi, I would like to shift some pixels in an image (Ny,Nx,Nc) given a 2D shift map (Ny,Nx).
I can easily do it with loops but I am having troubles to vectorize it:
% test shift of image with a map
clear all
close all
% example of image (vertical gradient) + horizontal red stripe
img=repmat(uint8((1:1980)'*255/1980),[1,2880,3]);
img(800:900,:,1)=255;
figure
imagesc(img)
title('original image')
% example of shift map (vertical gradient) +vertical stripe
shift_map=repmat((1:1980)'*1/4,[1,2880]);
shift_map(:,1000:1500)=255;
figure
imagesc(shift_map)
title('original shift map')
%% with loops
img_out_1=inf(size(img));
tic
for x=1:size(img,2)
for y=1:size(img,1)
indx_new=round(x-shift_map(y,x));
if 0<indx_new && indx_new<=size(img,2)
img_out_1(y,indx_new,:)=img(y,x,:);
end
end
end
% median filter to smooth the missing values
img_out_1=medfilt1(img_out_1,3,[],2);
toc
figure
imagesc(uint8(img_out_1))
title('final image')
I have managed to remove the loop on x and it is already much faster:
%% with loop on y only
img_out_2=inf(size(img));
tic
Nx=size(shift_map,2);
x=linspace(1,Nx,Nx);
for y=1:size(img,1)
indx_new=round(x-shift_map(y,:));
ind=find(0<indx_new & indx_new<Nx);
img_out_2(y,indx_new(ind),:)=img(y,x(ind),:);
end
img_out_2=medfilt1(img_out_2,3,[],2);
toc
figure
imagesc(uint8(img_out_2))
title('final image 2')
Naively I tried a similar approach to remove the loop on x, but I am getting very confused as my inddices ind_x becomes a matrix. Obviously img_out_3(yy(ind),indx_new(ind),:) fails with Requested 5212348x5212348x3 (75908.1GB) array exceeds maximum array size preference. Creation of arrays greater than this limit may take a long time and cause MATLAB to become unresponsive. See array size limit or preference panel for more information.
img_out_3=inf(size(img));
tic
Nx=size(img,2);
Ny=size(img,1);
Nc=size(img,3);
x=linspace(1,Nx,Nx);
y=linspace(1,Ny,Ny);
[yy,xx]=meshgrid(y,x);
indx_new=round(x-shift_map);
ind=find(0<indx_new & indx_new<Nx);
img_out_3(yy(ind),indx_new(ind),:)=img(yy(ind),xx(ind),:);
img_out_3=medfilt1(img_out_3,3,[],2);
toc
figure
imagesc(uint8(img_out_3))
title('final image 3')
Thanks for the heads up,
Matt
댓글 수: 2
KALYAN ACHARJYA
2019년 9월 17일
편집: KALYAN ACHARJYA
2019년 9월 17일
Shifting pixels in an image without loops
Sometimes simple representation of the problemmis much simpler to undestand than actual code.
Can you share the detail, it would be much easier to understand?
답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Image Processing and Computer Vision에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!