title: Separating Background and Foreground
body: <p>I am new to Matlab and to Image Processing as well. I am working on separating background and foreground in images like this</p>
  
  <p><img src="https://i.stack.imgur.com/tgedG.jpg" alt="passport image blue background"></p>
  
  <p>I have hundreds of images like this, found <a href="http://mmlab.ie.cuhk.edu.hk/facesketch.html" rel="nofollow noreferrer">here</a>. By trial and error I found out a threshold (in RGB space): the red layer is always less than 150 and the green and blue layers are greater than 150 where the background is.</p>
  
  <p>so if my RGB image is <code>I</code> and my <code>r</code>,<code>g</code> and <code>b</code> layers are</p>
  
  <pre><code>redMatrix = I(:,:,1);
  greenMatrix = I(:,:,2);
  blueMatrix = I(:,:,3);
  </code></pre>
  
  <p>by finding coordinates where in red, green and blue the values are greater or less than 150 I can get the coordinates of the background like</p>
  
  <pre><code>[r1 c1] = find(redMatrix &lt; 150);
  [r2 c2] = find(greenMatrix &gt; 150);
  [r3 c3] = find(blueMatrix &gt; 150);
  </code></pre>
  
  <p>now I get coordinates of thousands of pixels in <code>r1,c1,r2,c2,r3 and c3</code>.</p>
  
  <p><strong>My questions:</strong></p>
  
  <ol>
  <li><p>How to find common values, like the coordinates of the pixels where red is less than 150 and green and blue are greater than 150? 
  I have to iterate every coordinate of <code>r1</code> and <code>c1</code> and check if they occur in <code>r2 c2</code> and <code>r3 c3</code> to check it is a common point. but that would be very expensive.
  <strong>Can this be achieved without a loop</strong> ?</p></li>
  <li><p>If somehow I came up with common points like <code>[commonR commonC]</code> and <code>commonR</code> and <code>commonC</code> are both of order <code>5000 X 1</code>, so to access this background pixel of Image <code>I</code>, I have to access first <code>commonR</code> then <code>commonC</code> and then access image <code>I</code> like</p>
  
  <p><code>I(commonR(i,1),commonC(i,1))</code></p></li>
  </ol>
  
  <p>that is expensive too. So again my question is can this be done without loop.</p>
  
  <p>Any help would be appreciated.</p>
  
  <p><strong>I got solution with @Science_Fiction answer's</strong></p>
  
  <p>Just elaborating his/her answer</p>
  
  <p>I used </p>
  
  <pre><code>mask = I(:,:,1) &lt; 150 &amp; I(:,:,2) &gt; 150 &amp; I(:,:,3) &gt; 150;
  </code></pre>