一,java代码,收集Bitmap 信息
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnProc;
private ImageView imageView;
private Bitmap bmp;
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
btnProc = (Button) findViewById(R.id.btn_gray_process);
imageView = (ImageView) findViewById(R.id.image_view);
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.test7);
imageView.setImageBitmap(bmp);
btnProc.setOnClickListener(this);
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public static native int[] grayProc(int[] pixels, int w, int h);
@Override
public void onClick(View view) {
int w = bmp.getWidth();
int h = bmp.getHeight();
int[] pixels = new int[w*h];
bmp.getPixels(pixels, 0, w, 0, 0, w, h);
long startTime = System.currentTimeMillis();
int[] resultInt = grayProc(pixels, w, h);
long endTime = System.currentTimeMillis();
Log.e("JNITime",""+(endTime-startTime));
Bitmap resultImg = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
//(@ColorInt int[] pixels, int offset, int stride,int x, int y, int width, int height)
resultImg.setPixels(resultInt, 0, w, 0, 0, w, h);
imageView.setImageBitmap(resultImg);
}
}
二,jni实现
using namespace std;
using namespace cv;
void printMAtMessage(Mat &mat);
extern “C”
JNIEXPORT jintArray JNICALL
Java_com_example_dgxq008_opencv_1readpixel_MainActivity_grayProc(JNIEnv *env, jclass type
, jintArray pixels_
, jint w
, jint h) {
jint* pixels = env->GetIntArrayElements(pixels_, NULL);
if (pixels==NULL){
return 0;
}
//图片一进来时是ARGB 通过mat转换BGRA
Mat img(h,w,CV_8UC4,(uchar *)pixels); //pixels 操作的是同一份数据
printMAtMessage(img);
Mat temp;
//转化为单通道灰度图,并打印信息
cvtColor(img,temp,COLOR_RGBA2GRAY);
printMAtMessage(temp);
//转化为四通道。特别注意:在调用ov图像处理函数时,一定要好好考虑一下图片的位数和通道.否则可能出现各种问题.
cvtColor(temp,temp,COLOR_GRAY2BGRA);
printMAtMessage(temp);
uchar* tempData = temp.data;
//对应数据指针
int size = w*h;
jintArray result = env->NewIntArray(size);
//env->SetIntArrayRegion(result,0,size,pixels);
env->SetIntArrayRegion(result, 0, size, (const jint *) tempData);
env->ReleaseIntArrayElements(pixels_, pixels, 0);
return result;
}
void printMAtMessage(Mat &mat) {
LOGD(“***************************Mat信息开始************************”);
LOGD(“mat.rows %d”,mat.rows);
LOGD(“mat.cols %d”,mat.cols);
LOGD(“mat.total %d”,mat.total());
LOGD(“mat.channels %d”,mat.channels());
LOGD(“mat.depth %d”,mat.depth());
LOGD(“mat.type %d”,mat.type());
LOGD(“mat.flags %d”,mat.flags);
LOGD(“mat.elemSize %d”,mat.elemSize());
LOGD(“mat.elemSize1 %d”,mat.elemSize1());
LOGD(“***************************Mat信息结束************************”);
}
重要的事情说三遍:在调用opencv图像处理函数时,一定要好好考虑一下图片的尺寸和通道.否则可能出现各种问题.