MATLAB Answers

0

Store a group of points (given x, y, and value) into image efficiently

Asked by Yousef Atoum on 3 Oct 2019
Latest activity Commented on by Guillaume
on 7 Oct 2019
I have a matrix M with size m x 3 , where m is the total number of points (thousands of points). The three columns correspond to x, y and value. I want to map the values into an image efficiently. This task is very easy, but I need to speed up the process. I came up with the following two approaches:
First approach (Testing on 3600 points, I got a run time of 0.07 seconds.)
a = M(:,2);
b = M(:,1);
c = M(:,3);
img= accumarray ([a(:),b(:)],c(:));
img(1000,1) = 0;
img(1,1000) = 0;
Second approach (Testing on 3600 points, I got a run time of 0.04 seconds.)
img = zeros(1000,1000);
for i = 1 : size(M,1)
img(M(i,2),M(i,1)) = M(i,3);
end
parfor is not an option here in the second approach.
Does anyone know how to make this process faster?
Please note that I excute this code 50 times per frame obtained from a camera, resulting with a 2 second run time per frame.

  2 Comments

Can anyone make this task faster?
As I said, it's unlikely you'll find anything faster. Your loop code and my answer do the bare minimum: memory allocation (with zeros) then simple memory copy using an offset. At this point, the only thing that could make it faster is if the data to be copied is ordered with regards to the destination.

Sign in to comment.

1 Answer

Answer by Guillaume
on 3 Oct 2019
 Accepted Answer

img = zeros(1000, 1000);
img(M(:, 2) + 1000 * (M(:, 1) - 1)) = M(:, 3);

  2 Comments

Thanks Guillaume! I like your answer!
However, It did not improve the efficency. It gave me the same run speed as my for loop in my second approach (with a slight average speed up of 0.001).
Other than resorting to mex, I don't see how you can get any faster. Even with a mex, I'm not convinced you'll get any improvement.

Sign in to comment.