title: Matlab Least Squares approximation with Constraints for Two independent variables (x,y coordinates)
body: <p>I have a couple of binary images of outdoor paths and am required to get a fine outline of the roads, however, due to noisy pixels still remaining, I am unable to trace an accurate outline of the road. I calculated the midpoints between start and end points from <code>houghlines</code> function in <code>Matlab</code>, and have been able to separate the Left and Right points of the road. So, my idea was to fit a linear approximation of the Left and Right points so that I will be able to either remove the noisy pixels at both sides and separate out the road region cleanly. </p>
  
  <p><img src="https://i.stack.imgur.com/QzTEO.jpg" alt="Examples of good and bad line fits of left and right sides of two roads"></p>
  
  <p><strong>Problem:</strong> As you can see in the pictures, the straight line that fits is not along the longest axis of the scattered (x,y) points (red) and therefore a bad fit. Some sides of the roads were very good fit. The output approximation of the <a href="http://www.mathworks.com.au/matlabcentral/fileexchange/34765-polyfitn" rel="nofollow noreferrer">polyfitn</a> or <code>polyfit</code> function starts along the shorter scatter regions. I have found several code examples for least squares approximation with constraint (start and end) but found examples only for 1D independent variable type problems. </p>
  
  <p>Here is the Matlab code I used to produce the outputs.</p>
  
  <pre><code>imshow(binarizedimage320x240);        % Binary 320x240 image
  rightPoints     % show rightPoint (x,y) coordinates from Hough Transform lines 
  
  sizeRt = size(rightPoints, 1);
  x = zeros(sizeRt, 1);
  y = zeros(sizeRt, 1);
  
  for k = 1:sizeRt
      x(k) = rightPoints(k,1);
      y(k) = rightPoints(k,2);
  end
  x               % show x values
  y               % show y values
  
  
  % Linear fitting
  p = polyfitn(x,y,'constant x+y')    % show p
  xi = 1:2:300;
  yi = polyvaln(p, xi);
  
  plot(x, y, 'ro', xi, yi, 'b-', 'LineWidth', 3);
  </code></pre>
  
  <p><strong>Variables:</strong></p>
  
  <pre><code>rightPoints =
    205.0000  108.0000
    205.0000  162.5000
    205.0000  276.0000
    229.0000  123.5000
    229.0000  254.5000
    204.0000   87.5000
    215.0000  265.0000
    216.0000  121.0000
    216.0000  255.0000
  x =
     205
     215
     216
     229
     205
     229
     216
     205
     204
  y =
    276.0000
    265.0000
    255.0000
    254.5000
    162.5000
    123.5000
    121.0000
    108.0000
     87.5000
  p = 
        ModelTerms: [2x1 double]
      Coefficients: [-152.6022 1.5730]
      ParameterVar: [3.7729e+05 8.2396]
      ParameterStd: [614.2421 2.8705]
                R2: 0.0411
        AdjustedR2: -0.0958
              RMSE: 71.6719
          VarNames: {'x+y'}
  </code></pre>
  
  <p>Any help would be highly appreciated. Thanks.</p>