Is it possible to loop through and set image pixels with a parfor loop?
Show older comments
This code transforms a 360 degree image, but it is it slow with images at high resolutions. I was wondering if it was possible to convert one of the loops to a parfor loop to cut down on the time it takes to run the transformations.
Below is the code:
% loop through every pixel of am image
for row = 1 : width
% find pixel theta (elevation)
theta = (90/width) * (row + (row-1));
% transform theta into z cartesian coordinates
z = cosd(theta);
for col = 1 : 1: length
% find pixel psi (azimuth)
psi = (180/length) * (col + (col-1)) - 180;
% transform theta and psi into x and y cartesian coordinates
x = sind(theta) * cosd(psi);
y = sind(theta) * sind(psi);
% roll transformation
yNew = y * cosd(roll) - z * sind(roll);
zNew = y * sind(roll) + z * cosd(roll);
% pitch transformation
xNew = x * cosd(-pitch) + zNew * sind(-pitch);
zNew = zNew * cosd(-pitch) - x * sind(-pitch);
% yaw transformation
xYaw = xNew;
xNew = xYaw * cosd(yaw) - yNew * sind(yaw);
yNew = xYaw * sind(yaw) + yNew * cosd(yaw);
% transform x, y, and z back to spherical coordinates
psiNew = atan2d(yNew, xNew);
thetaNew = acosd(zNew);
% find new pixel row from theta
rowNew = round((thetaNew*width)/180 + 0.5);
% find new pixel column from psi
colNew = round((psiNew*length)/360 + length/2 + 0.5);
% map pixels from the original image to a new one
try
transformedImage(row, col, :) = app.newImage(rowNew, colNew, :); % THIS WONT WORK W/ A PARFOR LOOP
catch
disp("Psi/theta out of bounds:");
disp(psiNew + ", " + thetaNew);
disp(rowNew + ", " + colNew);
end
end
end
1 Comment
In general it is best not to use loops through matrices, that is the whole power of Matlab that considers everything a matrix. I.e., you can run through every pixel of an image and compare to a certain value:
myImage = rand(32,32);
for k1=1:32
for k2=1:32
myImage2(k1,k2) = myImage(k1,k2)>0.5;
end
end
imagesc(myImage2)
Or you can simply work as matrices:
myImage3 = (myImage>0.5);
imagesc(myImage3)
Thus, try to avoid loops and work with your data as a matrix.
Accepted Answer
More Answers (1)
Matt J
on 2 Aug 2022
1 vote
Categories
Find more on Image Category Classification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
