【问题标题】:Replace colors in an image without having to iterate through all pixels无需遍历所有像素即可替换图像中的颜色
【发布时间】:2018-06-10 14:30:34
【问题描述】:

假设我有一张这样的图片(实际上,我有很多,但让我们保持简单) example picture 我想用绿色替换背景颜色(那是不是道路的颜色)。

为此,我必须遍历地图中的所有像素并替换与我要删除的颜色匹配的像素。

但如你所想,我的图片不是简单的 256x256 图片,而是稍大一些,为 1440p,性能下降明显。

如何在不遍历所有像素的情况下替换所有不需要的像素。

我正在使用 Processing 3 - Java(Android),我目前正在使用这段代码:

for (x = 0; x < img.width; x++){
    for (int y = 0; y < img.height; y++) {
         //Color to transparent
         int index = x + img.width * y;
         if (img.pixels[index] == -1382175 || img.pixels[index] == 14605278 || img.pixels[index] == 16250871) {
            img.pixels[index] = color(0, 0, 0, 0);
         } else {
            img.pixels[index] = color(map(bright, 0, 255, 64, 192));
         }
    }
}

【问题讨论】:

    标签: java android image iteration processing


    【解决方案1】:

    用这个解决了:

    private PImage swapPixelColor(PImage img, int old, int now) {
        old &= ~0x00000000;
        now &= ~0x00000000;
    
        img.loadPixels();
        int p[] = img.pixels, i = p.length;
    
        while (i-- != 0) if ((p[i]) == old) p[i] = now;
    
        img.updatePixels();
        return img;
    }
    

    它就像一个魅力,几乎不需要时间:

    Swapped colors in 140ms // That's replacing it three times(different colors ofc)
    

    【讨论】:

    • 这不是还在迭代每个像素吗?唯一真正的区别是您正在缓存这些值,而不是在循环的每次迭代中重新创建它们,对吧?
    • 你是对的,但它足够快,很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多