- <span style="font-size:24px;"><span style="font-size:18px;">#include <jni.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <opencv2/opencv.hpp>
- using namespace cv;
- IplImage * change4channelTo3InIplImage(IplImage * src);
- void imageAdjust(IplImage * src,IplImage * dst);
- void Grayview(IplImage * src,int * dst,int width,int high);
- extern "C" {
- JNIEXPORT jintArray JNICALL Java_jojo_testopencv_LibImgFun_ImgFun(
- JNIEnv* env, jobject obj, jintArray buf, int w, int h);
- JNIEXPORT jintArray JNICALL Java_jojo_testopencv_LibImgFun_ImgFun(
- JNIEnv* env, jobject obj, jintArray buf, int w, int h) {
- jint *cbuf;
- cbuf = env->GetIntArrayElements(buf,NULL);
- if (cbuf == NULL) {
- return 0;
- }
- Mat myimg(h, w, CV_8UC4, (unsigned char*) cbuf);
- IplImage image=IplImage(myimg);
- IplImage* image3channel = change4channelTo3InIplImage(&image);
- IplImage* pCannyImage=cvCreateImage(cvGetSize(image3channel),IPL_DEPTH_8U,1);
- IplImage* pGrayImage=cvCreateImage(cvGetSize(image3channel),IPL_DEPTH_8U,1);</span></span>
- <span style="font-size:24px;"><span style="font-size:18px;"> cvCvtColor(image3channel,pGrayImage,CV_RGB2GRAY);//彩色图转换为灰度图</span></span>
如上,使用jni调用C++代码处理图片时,现将得到的原图转为四通道IplImage类型,再转为三通道。接下来使用cvCvtColor()方法将三通道彩图转为单通道灰度图,以为这样得倒的灰度图可以直接传给java程序,如下:
- <span style="font-size:24px;">int* outImage=new int[w*h];
- for(int i=0;i<w*h;i++)
- {
- outImage[i]=(int)pGrayImage->imageData[i];
- }
- int size = w * h;
- jintArray result = env->NewIntArray(size);
- env->SetIntArrayRegion(result, 0, size, outImage);
- env->ReleaseIntArrayElements(buf, cbuf, 0);
- return result;</span>
查资料才知道是自己对Iplimage类理解有误,就算是单通道,存储格式还是cv_RGB(r,g,b)
使用如下函数进行转换
- void Grayview(IplImage * src,int * dst,int width,int high){
- int alpha = 0xFF << 24;
- int w = width,h = high;
- for (int i = 0; i<w*h; i++) {
- // 获得像素的颜色
- int color = (int)src->imageData[i];
- int red = ((color & 0x00FF0000) >> 16);
- int green = ((color & 0x0000FF00) >> 8);
- int blue = color & 0x000000FF;
- color = (red + green + blue) / 3;
- color = alpha | (color << 16) | (color << 8) | color;
- dst[i] = color;
- }
- }
- int* outImage=new int[w*h];
- Grayview(enImage,outImage,w,h);
- int size = w * h;
- jintArray result = env->NewIntArray(size);
- env->SetIntArrayRegion(result, 0, size, outImage);
- env->ReleaseIntArrayElements(buf, cbuf, 0);
- return result;