static float bwImageSimilarityResized(BWImage a, BWImage b, float similarityRequired) {
  int aw = a.w(), ah = a.h();
  int bw = b.w(), bh = b.h();
  int wp = max(aw, bw), hp = max(ah, bh);
  float ratio1 = ((float) aw)/ah, ratio2 = ((float) bw)/bh;
  float mismatch = ratio1/ratio2;
  if (mismatch < 1f) mismatch = 1f/mismatch;
  float factor = wp*hp/mismatch; // ratio mismatch punishment (greater mismatch => factor smaller => returned difference bigger)
  float maxError = (1f-similarityRequired)*factor;
  float diff = 0;
  for (int y = 0; y < hp; y++)
    for (int x = 0; x < wp; x++) {
      diff += Math.abs(
        a.getPixel(x*aw/wp, y*ah/hp)-
        b.getPixel(x*bw/wp, y*bh/hp));
      if (diff > maxError) ret similarityRequired-0.001f;
    }
  ret 1f-diff/factor;
}