1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // Native function to extract contrast ratio from image (handed down as ByteBuffer).
18 
19 #include "contrast.h"
20 
21 #include <math.h>
22 #include <string.h>
23 #include <jni.h>
24 #include <unistd.h>
25 #include <android/log.h>
26 
27 jfloat
Java_androidx_media_filterfw_samples_simplecamera_ContrastRatioFilter_contrastOperator(JNIEnv * env,jclass clazz,jint width,jint height,jobject imageBuffer)28 Java_androidx_media_filterfw_samples_simplecamera_ContrastRatioFilter_contrastOperator(
29     JNIEnv* env, jclass clazz, jint width, jint height, jobject imageBuffer) {
30 
31     if (imageBuffer == 0) {
32       return 0.0f;
33     }
34     float total = 0;
35     const int numPixels = width * height;
36     unsigned char* srcPtr = static_cast<unsigned char*>(env->GetDirectBufferAddress(imageBuffer));
37     float* lumArray = new float[numPixels];
38     for (int i = 0; i < numPixels; i++) {
39         lumArray[i] = (0.2126f * *(srcPtr + 4 * i) + 0.7152f *
40             *(srcPtr + 4 * i + 1) + 0.0722f * *(srcPtr + 4 * i + 2)) / 255;
41         total += lumArray[i];
42     }
43     const float avg = total / numPixels;
44     float sum = 0;
45 
46     for (int i = 0; i < numPixels; i++) {
47         sum += (lumArray[i] - avg) * (lumArray[i] - avg);
48     }
49     delete[] lumArray;
50     return ((float) sqrt(sum / numPixels));
51 }
52