title: How to sort image blocks by to minimize the differences between them?
body: <p>I have a list of small image blocks. All of them are the same size (eg : 16x16). They are black and white, with pixel values between 0-255. I would like to sort those images to minimize the the difference between them.</p>
  
  <p>What I have in mind is to compute the <a href="https://en.wikipedia.org/wiki/Mean_absolute_difference" rel="nofollow noreferrer">mean absolute difference</a> (MAD) of pixels between adjacent blocks (eg : block N vs block N+1, block N+1 vs block N+2, ...). 
  From this I can calculate the sum of those MAD values (eg : sum = mad1 + mad2 + ...). What I would like is to find the ordering that minimize that sum.</p>
  
  <p>Before :</p>
  
  <p><a href="https://i.stack.imgur.com/vE8CD.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vE8CD.gif" alt="enter image description here"></a></p>
  
  <p>After : (this was done by hand only to provide an example, there is probably a better ordering for those blocks, especially the ones with vertical stripes)</p>
  
  <p><a href="https://i.stack.imgur.com/137GD.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/137GD.gif" alt="enter image description here"></a></p>