title: Best-fit a rectangle over a 2D blob
body: <p>I have a binary blob (see image), and I want to fit a rectangle <em>of known width and height</em> over it.</p>
  
  <p>How can I find the optimal fitting rectangle, i.e. the one where the maximum of foreground pixels are inside and the maximum amount of background pixels are outside?</p>
  
  <p>(This is my preliminary definition of best-fit, I am open to other suggestions)</p>
  
  <p>I am looking for rectangles of a known size, but if there is a solution for arbitrary sizes, that would be great too.</p>
  
  <p>Example blobs:
  <img src="https://i.stack.imgur.com/q8JFw.png" alt="enter image description here"></p>
  
  <p>I want to find these rectangles:
  <img src="https://i.stack.imgur.com/XOQT6.png" alt="enter image description here"></p>
  
  <p>My ideas so far included </p>
  
  <ul>
  <li>start with the minimum enclosing rectangle; but that is not a good match for these blobs</li>
  <li>maximum enclosed rectangle; same problem, plus I do not have an algorithm for that</li>
  <li>find rectangle sides with hough transform; the data is too noisy for that.</li>
  </ul>
  
  <p>I realize that there could be multiple rectangles for the same blob that fit my criteria, ideally I would want some algorithm that can find all candidates (thought since that is probably harder, I'd be happy with a way to find only one candidate):
  <img src="https://i.stack.imgur.com/Wo49I.png" alt="enter image description here">
  <img src="https://i.stack.imgur.com/5jT6o.png" alt="enter image description here"></p>
  
  <p>I am using mostly opencv and cvBlobLib to process my data, but I am open for any general solution.</p>