您的代码查找“最红”像素,即具有最高红色值的像素。我认为这实际上不是您所需要的,但如果我错了,请纠正我。
你也把事情复杂化了。让我们从一个Bitmap
和两个循环:
int redThreshold = 200; // adjust this to your needs
List<int[]> redPixels = new ArrayList<>(); // redPixels.get(int)[0] = x, redPixels.get(int)[1] = y
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
for(int x = 0; x < thumbnail.getWidth(); x++) // x is row
for(int y = 0; y < thumbnail.getHeight(); y++) // y is col
if(Color.red(thumbnail.getPixel(x, y)) > redThreshold) {
redPixels.add(new int[]{x, y});
System.out.println(String.format("Pixel at (%d, %d) has a red value exceeding our threshold of %d!", x, y, redThreshold);
}
正如 @Eliseo 在他的评论中暗示的那样,根据您的实际需求,您可能需要检查其他两种颜色是否也低于某个阈值,因为这将拾取诸如白色的颜色(r = 255,g = 255 ,b=255 是白色!)。
那么,我们如何寻找视觉红色呢?你我都会看到并同意的东西就是“红色”。好吧,让我们确保红色值与绿色或蓝色中较大的值具有适当的比率;蓝色和绿色在彼此的阈值内,否则我们会捕捉到粉色和橙色。像这样的事情:
int thresholdRatio = 2;
int threshold = 15;
List<int[]> redPixels = new ArrayList<>();
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
for(int x = 0; x < thumbnail.getWidth(); x++)
for(int y = 0; y < thumbnail.getHeight(); y++) {
Color color = thumbnail.getPixel(x, y);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
if((r > (Math.max(g, b) * thresholdRatio)) && (Math.abs(g - b) < threshold)) {
redPixels.add(new int[]{x, y});
System.out.println(String.format("Pixel at (%d, %d) has a red value more than %d times the max(green, blue) value, and the green and blue value are also within %d points!", x, y, thresholdRatio, threshold);
}
}
这将捕获非常浅和非常深的红色阴影。如果您需要捕捉非常特定的红色色调,请添加天花板和地板阈值。
想要可视化捕获了哪些像素?如果位图是可变的,我们就可以。
Random rand = new Random();
Color getRandomColor() {
int[] rgb = new int[3];
for(int i = 0; i < rgb.length; i++) {
rgb[i] = rand.nextInt(256);
}
return Color.rgb(rgb[0], rgb[1], rgb[2]);
}
boolean transformRedPixels(Bitmap bm, List<int[]> redPixels) {
for(int[] coords : redPixels) {
bm.setPixel(coords[0], coords[1], getRandomColor()); // This will set each pixel caught to a new random color
}
return bm.isMutable();
}
让我知道这是否适合您的需求。快乐编码:)