I segmented an image into N superpixels and constructed a graph based on that in which each superpixel is considered as a node. The information about neighbor superpixels is stored in glcms
array. The weight between each pair of neighboring superpixels is stored in matrix W
.
Finally, I want to compute geodesic distance between non-adjacent superpixels using graphshortestpath
function. The following code does the mentioned process, however it is very time-consuming. Specifically, the last section of the code that computes geodesic distance takes more time than expected (more than 15 sec).
Img=imread('input.jpg');
[rows, columns, numberOfColorChannels] = size(Img);
[L,N] = superpixels(Img,250);
%Identifying neighborhood relationships
glcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[1,N],'Offset', [0,1;1,0]); %Create gray-level co-occurrence matrix from image
glcms = sum(glcms,3); % add together the two matrices
glcms = glcms + glcms.'; % add upper and lower triangles together, make it symmetric
glcms(1:N+1:end) = 0; % set the diagonal to zero, we don't want to see "1 is neighbor of 1"
data = zeros(N,3);
for labelVal = 1:N
redIdx = idx{labelVal};
greenIdx = idx{labelVal}+numRows*numCols;
blueIdx = idx{labelVal}+2*numRows*numCols;
data(labelVal,1) = mean(Img(redIdx));
data(labelVal,2) = mean(Img(greenIdx));
data(labelVal,3) = mean(Img(blueIdx));
end
Euc=zeros(N);
% Euclidean Distance
for i=1:N
for j=1:N
if glcms(i,j)~=0
Euc(i,j)=sqrt(((data(i,1)-data(j,1))^2)+((data(i,2)-data(j,2))^2)+((data(i,3)-data(j,3))^2));
end
end
end
W=zeros(N);
W_num=zeros(N);
W_den=zeros(N);
OMG1=0.1;
for i=1:N
for j=1:N
if(Euc(i,j)~=0)
W_num(i,j)=exp(-OMG1*(Euc(i,j)));
W_den(i,i)=W_num(i,j)+W_den(i,i);
end
end
end
for i=1:N
for j=1:N
if(Euc(i,j)~=0)
W(i,j)=(W_num(i,j))/(W_den(i,i)); % Connectivity Matrix W
end
end
end
s_star_temp=zeros(N); %temporary variable for geodesic distance measurement
W_sparse=zeros(N);
W_sparse=sparse(W);
for i=1:N
for j=1:N
if W(i,j)==0 & i~=j;
s_star_temp(i,j)=graphshortestpath(W_sparse,i,j); % Geodesic Distance
end
end
end
The question is how to optimize the code to be more efficient , i.e. less time-consuming.