title: MATLAB Piecewise Linear Transformation Function
body: <p>I have generated a function to apply a piecewise linear transformation to an image. Based on this function, I am unsure if it is performing correctly. Sometimes the entire image shows up as white and all pixels listed as 255. Other times, the output image appears but results vary. Due to the varying results, I believe there is an issue with my function. The code for the function is here:</p>
  
  <pre><code>function T = piecewise_transform(f,n,r1,s1,r2,s2,r3,s3)
  
  % breakpoints: (0,0),(r1,s2),(r2,s2),(r3,s3),((L-1),(L-1))
  
  % to get alpha, beta, etc, don't suppress echoing (remove ; )
  
  % find the parameters of each line
  
  L = 2^n;
  
  % s = a*r+b
  
  a1 = ((s1-0)/(r1-0));
  b1 = ((s1/r1)); 
  a2 = ((s2-s1)/(r2-r1));
  b2 = ((s1*r2)-(s2*r1)/(r2-r1)); 
  a3 = ((s3-s2)/(r3-r2));
  b3 = (((s3-s2)/(r3-r2))*(s2/r2));
  a4 = (((L-1)-s3)/((L-1)-r3));
  b4 = (((L-1)-s3)/((L-1)-r3)*(s3/r3));
  
  % put all parameters in two vectors
  
  A = [a1,a2,a3,a4]
  B = [b1,b2,b3,b4]
  
  [row,col] = size(f);
  T = f;
  
  for i = 1:row
      for j=1:col
  
      % find which line to use
  
      %line 1
      if f(i,j) &lt; r1
          flag = 1;
      end
  
      % line 2
      if f(i,j) &gt; r1 &amp;&amp; f(i,j)&lt;r2
         flag = 2;
      end
  
      % line 3
      if f(i,j) &gt; r2 &amp;&amp; f(i,j)&lt;r3
         flag = 3;
      end
  
      % line 4
      if f(i,j) &gt; r3 &amp;&amp; f(i,j)&lt;(L-1)
         flag = 4;
      end
  
      T(i,j) = (A(flag)*f(i,j) + B(flag));
     end
  end
  
  T = uint8(T);
  
  imshow(T)
  </code></pre>
  
  <p>Here are the results of some of my tests:</p>
  
  <p><img src="https://i.stack.imgur.com/QBoLp.png" alt="enter image description here"></p>
  
  <p><a href="https://i.stack.imgur.com/vm0lz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vm0lz.png" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/KrsFI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KrsFI.png" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/WxrZn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxrZn.png" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/h0DCj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h0DCj.jpg" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/SZATO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SZATO.jpg" alt="enter image description here"></a></p>
  
  <p>Based on my code, why am I receiving varying results? </p>