title: how to build a graph of connected components of an image?
body: <p>I am having an image.i would like to convert this image into graph.Pixels are the nodes and edges represents 8-neighbourhood.
  i tried </p>
  
  <pre><code>I=imread('cameraman.tif');
  [r c]=size(I); 
  %r = 32; c = 32;
  %# Get the matrix size
  diagVec1 = repmat([ones(c-1,1); 0],r,1);  %# Make the first diagonal vector
  %#   (for horizontal connections)
  diagVec1 = diagVec1(1:end-1);             %# Remove the last value
  diagVec2 = [0; diagVec1(1:(c*(r-1)))];    %# Make the second diagonal vector
  %#   (for anti-diagonal connections)
  diagVec3 = ones(c*(r-1),1);               %# Make the third diagonal vector
  %#   (for vertical connections)
  diagVec4 = diagVec2(2:end-1);             %# Make the fourth diagonal vector
  rc = r*c;
  adj = spdiags([diagVec1;0],1,rc,rc);
  adj = adj + spdiags([diagVec2; zeros(c-1,1)], c-1, rc,rc);
  adj = adj + spdiags([diagVec3; zeros(c,1)], c, rc,rc);
  adj = adj + spdiags([diagVec4; zeros(c+1,1)], c+1, rc,rc);
  adj = adj + adj.';
  
  %# plot adjacency matrix
  subplot(121), spy(adj)
  
  %# plot connected points on grid
  [X Y] = meshgrid(1:c,1:r);
  X = X(:); Y = Y(:);
  [xx yy] = gplot(adj, [X Y]);
  subplot(122), plot(xx, yy, 'ks-', 'MarkerFaceColor','r')
  axis([0 r+1 0 c+1])
  %# add labels
  X = reshape(X',[],1) + 0.1; Y = reshape(Y',[],1) + 0.1;
  text(X, Y(end:-1:1), cellstr(num2str((1:r*c)')) )
  </code></pre>
  
  <p>i tried this code.But out of memory problem;works fine for 32*32 image.its not a duplicate question </p>