[英]How to detect all pixels of specific color (and similar ones) in a bitmap?
我正在處理Android Studio中的位圖圖像,並且我想知道如何檢測所有紅色像素為例,而不僅僅是檢測嚴格等於Color.RED的像素。 我只是舉一個紅色的例子,但是我想用所有可能的顏色來做。
I tried to do this:
...
int[] pixels = new int[width * height];
myBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
for (int i = 0; i < width * height; i++) {
if (pixels[i] == Color.RED) {
// color detected
}
...
但這不起作用,因為我的圖像不包含(255,0,0)的紅色像素,但包含可能是(251,30,77)或(239,23,42)的像素,這也就是“紅色“,等等。
那么我該怎么做呢? 我也嘗試過類似的東西:
int reference; // color as rgb
if ( (Color.red(pixels[i]) > Color.red(reference) - 20) &&
(Color.red(pixels[i]) < Color.red(reference) + 20 &&
...
{
// pixel detected
}
...
我假設(r +-20,g +-20,b + -20)是(r,g,b)的一部分(我的意思是,對於人眼)
關於我該怎么做的任何想法?
您可以接受所需顏色一定距離內的所有像素。 假設您想要RED,並且所有東西都在RED的10歐氏距離內:
boolean distance(int a, int b) {
return Math.sqrt(Math.pow(Color.red(a) - Color.red(b), 2) + Math.pow(Color.blue(a) - Color.blue(b), 2) + Math.pow(Color.green(a) - Color.green(b), 2));
}
....
int reference = Color.RED;
if (distance(reference, pixels[i]) < 10) {
//pixel accepted
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.