Clear Filters
Clear Filters

How can I optimize the the code below which assigns grey-scale color values to a color array from pixels in an image?

2 views (last 30 days)
Hi!
I am trying to optimise the code below, which is the only part of a program i have made which uses for loops, and as such is fairly time consuming.
The program essentially uses two cameras, with their positions calibrated and defined relative to the position of an object they are imaging. The object is created in the virtual space by importing it as a point cloud and converting this to a triangulated surface. The code uses information about the normal vector to each triangle on the surface to figure out whether each camera can actually "see" that point on the object in the real world, and then uses the relevant pixel data for that point (each point is mapped onto the image to find out which pixel refers to it) to assign the correct colour value to the color array for the point cloud.
Any advice would be appreciated, I'm fairly new to matlab and definitely new to the concept of eliminating for loops and code optimisation.
If i haven't explained the code clearly enough please let me know.
Thanks,
Toby
%Assign color to points if the surface faces towards the relevant camera
for m=1:numberoffaces
camera1vector=locationcamera1-P(m,:);
camera2vector=locationcamera2-P(m,:);
if (dot(camera1vector,F(m,:)))<0
colors(m)= imageGL(pixelposition1(m,2),pixelposition1(m,1));
colors(m)= imageGL(pixelposition1(m,2),pixelposition1(m,1));
colors(m)= imageGL(pixelposition1(m,2),pixelposition1(m,1));
elseif (dot(camera2vector,F(m,:)))<0
colors(m)= imageGR(pixelposition2(m,2),pixelposition2(m,1));
colors(m)= imageGR(pixelposition2(m,2),pixelposition2(m,1));
colors(m)= imageGR(pixelposition2(m,2),pixelposition2(m,1));
else
colors(m)= (0);
colors(m)= (0);
colors(m)= (0);
end
end

Answers (1)

Pratik
Pratik on 11 Jun 2024
Hi Toby,
As per my understanding, the provided code to assign grey scale values to a color array needs to be optimised.
There are two major scope for optimisation in the above code, removing redundancy and vectorization. For every condition in the code same operation gets exectued three times in a row. By doing it just once the speed of code can be increased by 3 times.
MATLAB is optimized for operations involving matrices and vectors. The process of revising loop-based, scalar-oriented code to use MATLAB matrix and vector operations is called vectorization. With help of precomputation and vectorization the for loop can be eliminated which can enhance the performance of the code.
Please refer to the following documentation of vectorization for more information:
I hope this helps!

Community Treasure Hunt

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

Start Hunting!