double determineRotation(BufferedImage img, double initialRotation, int blackWhiteBoundary) {
		int w = 0;
		int h = 0;
		if (img.getWidth() > img.getHeight()) {
			w = MAX_DIM;
			h = MAX_DIM * img.getHeight() / img.getWidth();
		} else {
			w = MAX_DIM * img.getWidth() / img.getHeight();
			h = MAX_DIM;
		}
		BufferedImage scaled = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics2D sg = scaled.createGraphics();
		sg.drawImage(img, 0, 0, w, h, null);
		BufferedImage out1 = new BufferedImage(IMAGE_H, IMAGE_H, BufferedImage.TYPE_INT_RGB);
		double bestRotation = initialRotation;
		double bestStdDev = 0.0;
		for (int t = 0; t < TILT_RANGE * 2; t++) {
			double tilt = (t - TILT_RANGE) * TILT_DELTA;
			Graphics2D g1 = out1.createGraphics();
			g1.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
			g1.setColor(Color.WHITE);
			g1.fillRect(0, 0, IMAGE_H, IMAGE_H);
			g1.translate(IMAGE_H / 2, IMAGE_H / 2);
			g1.rotate(tilt + initialRotation);
			g1.translate(-w / 2, -h / 2);
			g1.drawImage(scaled, 0, 0, null);
			
			Histogram ch = new Histogram(IMAGE_H / 2);
			for (int y = 0; y < IMAGE_H * 3 / 4; y++) {
				int contactsHorizontal = 0;
				for (int x = IMAGE_H / 4; x < IMAGE_H * 3 / 4; x++) {
					Color c = new Color(out1.getRGB(x, y));
					int intensity = (c.getRed() + c.getGreen() + c.getBlue()) / 3;
					if (intensity < blackWhiteBoundary) {
						contactsHorizontal++;
					}
				}
				ch.add(contactsHorizontal);
			}
						
			double stdDev = ch.stdDev();
			if (stdDev > bestStdDev) {
				bestRotation = initialRotation + tilt;
				bestStdDev = stdDev;
			}
		}
		
		return bestRotation;
	}