import android.graphics.Bitmap; import android.graphics.Color; public class DisparityMapGenerator { private static final int BLOCK_SIZE = 5; private static final int MAX_DISPARITY = 64; public static Bitmap generateDisparityMap(Bitmap leftImage, Bitmap rightImage) { int width = leftImage.getWidth(); int height = leftImage.getHeight(); Bitmap disparityMap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int bestDisparity = 0; int bestScore = Integer.MAX_VALUE; for (int d = 0; d < MAX_DISPARITY; d++) { int score = computeScore(leftImage, rightImage, x, y, d); if (score < bestScore) { bestScore = score; bestDisparity = d; } } int color = (int) (bestDisparity * (255.0 / MAX_DISPARITY)); disparityMap.setPixel(x, y, Color.rgb(color, color, color)); } } return disparityMap; } private static int computeScore(Bitmap leftImage, Bitmap rightImage, int x, int y, int disparity) { int score = 0; for (int dy = -BLOCK_SIZE; dy <= BLOCK_SIZE; dy++) { for (int dx = -BLOCK_SIZE; dx <= BLOCK_SIZE; dx++) { int leftX = x + dx; int leftY = y + dy; int rightX = leftX - disparity; int rightY = leftY; if (leftX >= 0 && leftX < leftImage.getWidth() && leftY >= 0 && leftY < leftImage.getHeight() && rightX >= 0 && rightX < rightImage.getWidth() && rightY >= 0 && rightY < rightImage.getHeight()) { int leftColor = leftImage.getPixel(leftX, leftY); int rightColor = rightImage.getPixel(rightX, rightY); int diff = Color.red(leftColor) - Color.red(rightColor); score += diff * diff; } } } return score; } }
沒有留言:
張貼留言