我在c ++ ndk中实现了Java图像过滤器代码,但结果不同。 两者的值都是70。
Java版:
public Bitmap applyContrastEffect(Bitmap src, double value) {
// image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// color information
int A, R, G, B;
int pixel;
// get contrast value
double contrast = Math.pow((100 + value) / 100, 2);
// scan through all pixels
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
// apply filter contrast for every channel R, G, B
R = Color.red(pixel);
R = (int) (((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if (R < 0) {
R = 0;
} else if (R > 255) {
R = 255;
}
G = Color.red(pixel);
G = (int) (((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if (G < 0) {
G = 0;
} else if (G > 255) {
G = 255;
}
B = Color.red(pixel);
B = (int) (((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if (B < 0) {
B = 0;
} else if (B > 255) {
B = 255;
}
int val = Color.argb(A, R, G, B);
// set new pixel color to output bitmap
bmOut.setPixel(x, y, val);
}
}
// return final image
return bmOut;
}
c ++版本:
int* ContrastFilter::procImage() {
double value = 70;
double contrast = pow((100 + value) / 100, 2);
int A, R, G, B;
for (int i = 0; i < width * height; ++i) {
//__android_log_print(ANDROID_LOG_VERBOSE, "Contrast Filter","The before color is %d", this->pixels[i]);
Color color(this->pixels[i]);
A = color.alpha();
R = color.R();
R = (int) (((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if (R < 0) {
R = 0;
} else if (R > 255) {
R = 255;
}
G = color.G();
G = (int) (((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if (G < 0) {
G = 0;
} else if (G > 255) {
G = 255;
}
B = color.B();
B = (int) (((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if (B < 0) {
B = 0;
} else if (B > 255) {
B = 255;
}
this->pixels[i] = ARGB2Color(A, R, G, B);
}
return this->pixels;
}
Java c ++接口:
public static Bitmap changeToContrast(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap returnBitmap = Bitmap.createBitmap(width, height, bitmap.getConfig());
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
int[] returnPixels = NativeFilterFunc.contrastFilter(pixels, width,
height);
returnBitmap.setPixels(returnPixels, 0, width, 0, 0, width, height);
return returnBitmap;
}
Java结果:
c ++结果:
我无法理解为什么结果不同。 当我调试时,我看到一些像素值不同,但为什么在计算公式相同时会发生这种情况?
答案 0 :(得分:8)
R = Color.red(pixel);
...
G = Color.red(pixel);
...
B = Color.red(pixel);
您正在为Java代码中的每种颜色取红色值。您可能希望将其调整为采用正确的值,如下所示:
R = Color.red(pixel);
...
G = Color.green(pixel);
...
B = Color.blue(pixel);
作为旁注:根据Java惯例,变量名称应以 lower 大小写字母开头。