由于性能原因,更好的像素计算方法

Dim*_*nis -2 java javafx

我有一个方法,它接受一个javafx.scene.paint.color参数并返回blackwhite作为一个color取决于brightness给定的color.

这是我的代码:

@Override
public Color getPixelColor(Color color) {
    return color.getBrightness() > cutOff ? Color.WHITE : Color.BLACK;
}
Run Code Online (Sandbox Code Playgroud)

因为这对每个要做pixelimage该方法可以利用根据的一会儿image size.(对于全高清图像,代码将运行200万条if语句)

所以我的问题是,如果有一种方法/计算,它会给你0(黑色)或1(白色)作为结果但不使用任何if陈述.

提前致谢.

Iły*_*sov 6

正如评论中所说 - 我怀疑这个特殊功能是瓶颈.但你仍然可以优化它.

如果你更深入并解编译getBrightness函数,你会发现它实际上是将R,G,B值转换为HSB然后只返回B.它使用com.sun.javafx.util.Utils.RGBtoHSB函数

进一步,在com.sun.javafx.util.Utils.RGBtoHSB中我们将看到计算亮度,你需要从R,G,B中选择最大值

double cmax = (r > g) ? r : g;
if (b > cmax) cmax = b;
brightness = cmax;
Run Code Online (Sandbox Code Playgroud)

所以,我们可以重复使用这些知识(没有数组分配,无用的色调/饱和度计算):

if ((clr.getRed() > cutoff) || (clr.getGreen() > cutoff) || (clr.getBlue() > cutoff)) {
    return Color.WHITE;
} else {
    return Color.BLACK;
}
Run Code Online (Sandbox Code Playgroud)

或进一步优化(以消除if语句):

private static final Color[] BW_VALUES = {Color.BLACK, Color.WHITE};

public static Color convertToBW_1(final Color clr, final double cutoff) {
    /**
     * rd will be 0, if red channel under cutoff, ie black. rd will be 1, if red channel is above cutoff, ie white
     */
    final byte rd = (byte) (Double.doubleToRawLongBits(cutoff - clr.getRed()) >>> 63);
    final byte gd = (byte) (Double.doubleToRawLongBits(cutoff - clr.getGreen()) >>> 63);
    final byte bd = (byte) (Double.doubleToRawLongBits(cutoff - clr.getBlue()) >>> 63);

    /**
     * if at least one value is 1, then return white.
     */
    return BW_VALUES[rd | gd | bd];
}
Run Code Online (Sandbox Code Playgroud)

根据我的快速测量 - 这个变种快了2倍,但你的里程可能会有所不同