【MediaTek X20开发板试用体验】8.MTX20开发板Android Studio+"高斯模糊"算法实现  

分享到:

xble
 xble
Level 1
注册时间:8年 前
帖子数: 15
2017年3月14日 上午9:32  

上个帖子里面实现了灰度图转换程序,本来是想实现“高斯模糊”算法只是程序一直有问题为了完成发帖就简化了程序。
“高斯模糊”算法,公式计算机图形学中有非常详细的介绍,我们这里通过EasyPR里面理解来说明一下。
平均模糊算法,就是将像素值替换为像素周围8个像素平均值的算法,如下图:
 
在平均模糊中周围像素的权值都是一样的都是1。如果周围像素的权值不一样,并且与二维的高斯分布的值一样那么就叫做高斯模糊。有兴趣的人可以自己查查什么是高斯分布值,高斯函数,权重矩阵等等知识,我们这里只是肤浅的学习概念和如何使用,有点像使用VS开发软件,我们只管知道微软提供的API如何使用就可以完成一般工作,当然搞清楚其背后的原理则是极好滴!

下面直接列出代码,只是在上个帖子的代码稍微修改而已。
MainActivity.java

  1. package com.example.gzh.myplatelocate;
  2. import android.graphics.Bitmap;
  3. import android.graphics.BitmapFactory;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.os.Bundle;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.ImageView;
  9. import android.widget.TextView;
  10. import org.opencv.android.Utils;
  11. import org.opencv.core.Mat;
  12. import static org.opencv.android.OpenCVLoader.initDebug;
  13. import static org.opencv.imgproc.Imgproc.COLOR_RGB2GRAY;
  14. import static org.opencv.imgproc.Imgproc.cvtColor;
  15. public class MainActivity extends AppCompatActivity {
  16.     static String TAG = "Myplatelocate";
  17.     ImageView show_image;
  18.     Bitmap srcBitmap;
  19.     Bitmap grayBitmap;
  20.     private long mRecognizerPtr = 0;
  21.     private static boolean flag = true;
  22.     PlateRecognizer MyPlateRecognizer;
  23.     @Override
  24.     protected void onCreate(Bundle savedInstanceState) {
  25.         super.onCreate(savedInstanceState);
  26.         setContentView(R.layout.activity_main);
  27.         // Example of a call to a native method
  28.         TextView tv = (TextView) findViewById(R.id.sample_text);
  29.         MyPlateRecognizer = new PlateRecognizer(this);
  30.         tv.setText(MyPlateRecognizer.stringFromJNI());
  31.         show_image = (ImageView) findViewById(R.id.imageView);
  32.         show_image.setImageResource(R.drawable.heidfk640);
  33.         findViewById(R.id.button_normal).setOnClickListener(new View.OnClickListener() {
  34.             @Override
  35.             public void onClick(View v) {
  36.                 //恢复
  37.                 backPic();
  38.             }
  39.         });
  40.         findViewById(R.id.button_gray).setOnClickListener(new View.OnClickListener() {
  41.             @Override
  42.             public void onClick(View v) {
  43.                 //变灰
  44.                // grayPic();
  45.                 Log.i(TAG, "setOnClickListener procSrc2Gray sucess...my_SobelOper");
  46.                 procSrc2Gray();
  47.             }
  48.         });
  49.     }
  50.     private void backPic(){
  51.         show_image.setImageResource(R.drawable.heidfk640);
  52.     }
  53.     private void grayPic(){
  54.         Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.heidfk640);
  55.         int w = bmp.getWidth();
  56.         int h = bmp.getHeight();
  57.         int[] pixels = new int[w*h];
  58.         bmp.getPixels(pixels, 0, w, 0, 0, w, h);
  59.         //recall JNI
  60.         int[] resultInt = MyPlateRecognizer.getGrayImage(pixels, w, h);
  61.         Bitmap resultImg = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
  62.         resultImg.setPixels(resultInt, 0, w, 0, 0, w, h);
  63.         show_image.setImageBitmap(resultImg);
  64.         Log.i(TAG, "procSrc2Gray sucess...11111111111");
  65.     }
  66.     public void procSrc2Gray(){
  67.         int nFalg_test = 2;
  68.         Mat rgbMat = new Mat();
  69.         Mat grayMat = new Mat();
  70.         srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.heidfk640);
  71.         grayBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.RGB_565);
  72.         Utils.bitmapToMat(srcBitmap, rgbMat);//convert original bitmap to Mat, R G B.
  73.           if(nFalg_test == 1)
  74.           {
  75.               String str1 = null;
  76.               str1 = String.format("call my_CvtColor rgbMat.channels()=%d", rgbMat.channels());
  77.               Log.i(TAG, str1);
  78.               MyPlateRecognizer.my_CvtColor(rgbMat, grayMat, COLOR_RGB2GRAY);//rgbMat to gray grayMat
  79.               // Then convert the processed Mat to Bitmap
  80.               Log.i(TAG, "call my_CvtColor sucess...=2=");
  81.           }
  82.           else {
  83.               String str1 = null;
  84.               str1 = String.format("call my_SobelOper rgbMat.channels()=%d", rgbMat.channels());
  85.               Log.i(TAG, str1);
  86.               MyPlateRecognizer.my_SobelOper(rgbMat, grayMat, COLOR_RGB2GRAY);//rgbMat to gray grayMat
  87.               // Then convert the processed Mat to Bitmap
  88.               Log.i(TAG, "call my_SobelOper sucess...=2=");
  89.           }
  90.         Utils.matToBitmap(grayMat, grayBitmap);
  91.         Log.i(TAG, "procSrc2Gray sucess...=3=");
  92.         show_image.setImageBitmap(grayBitmap);
  93.         Log.i(TAG, "procSrc2Gray sucess...");
  94.     }
  95.     @Override
  96.     protected void onResume() {
  97.         super.onResume();
  98.         if (initDebug()) {
  99.             Log.i(TAG, "OpenCV initialize success");
  100.         } else {
  101.             Log.i(TAG, "OpenCV initialize failed");
  102.         }
  103.     }
  104. }

复制代码

PlateRecognizer.java

  1. package com.example.gzh.myplatelocate;
  2. import android.content.Context;
  3. import android.util.Log;
  4. import org.opencv.core.Mat;
  5. /**
  6. * Created by gzh on 17-2-12.
  7. */
  8. public class PlateRecognizer {
  9.     // Used to load the 'native-lib' library on application startup.
  10.     static String TAG = "PlateRecognizer";
  11.     static {
  12.         System.loadLibrary("native-lib");
  13.        // System.loadLibrary("opencv_java3");
  14.     }
  15.     private Context mContext;
  16.     private String mSvmpath = "svm.xml";
  17.     private String mAnnpath = "ann.xml";
  18.     private boolean mRecognizerInited = false;
  19.     private long mRecognizerPtr = 0;
  20.     public PlateRecognizer(Context context) {
  21.         mContext = context;
  22.              mRecognizerPtr = initPR();
  23.             if (0 != mRecognizerPtr) {
  24.                 mRecognizerInited = true;
  25.         }
  26.     }
  27.     public void finalize() {
  28.         uninitPR(mRecognizerPtr);
  29.         mRecognizerPtr = 0;
  30.         mRecognizerInited = false;
  31.     }
  32.     public void my_SobelOper(Mat rgbMat, Mat grayMat, int COLOR_RGB2GRAY) {
  33.         Log.i(TAG, "my_SobelOper=1=");
  34.         mySobelOper(mRecognizerPtr, rgbMat.getNativeObjAddr(), grayMat.getNativeObjAddr());//rgbMat to gray grayMat
  35.         Log.i(TAG, "my_SobelOper=2=");
  36.     }
  37.     public void my_CvtColor(Mat rgbMat, Mat grayMat, int COLOR_RGB2GRAY) {
  38.         Log.i(TAG, "my_CvtColor=1=");
  39.         myCvtColor(rgbMat.getNativeObjAddr(), grayMat.getNativeObjAddr(), COLOR_RGB2GRAY);//rgbMat to gray grayMat
  40.         Log.i(TAG, "my_CvtColor=2=");
  41.     }
  42.     /**
  43.      * A native method that is implemented by the 'native-lib' native library,
  44.      * which is packaged with this application.
  45.      */
  46.     public static native String stringFromJNI();
  47.     //public static native String validate(long matAddrGr, long matAddrRgba);
  48.     //图像处理
  49.     private static native void myCvtColor(long thiz, long inputImage, long faces);
  50.     public static native int[] getGrayImage(int[] pixels, int w, int h);
  51.     public static native long initPR();
  52.     public static native long uninitPR(long recognizerPtr);
  53.     public static native void mySobelOper(long recognizerPtr, long inputImage, long faces);
  54. }

复制代码

native-lib.cpp

  1. #include <jni.h>
  2. #include <string>
  3. #include <stdio.h>
  4. #include <iostream>
  5. #include <string>
  6. #include "opencv2/opencv.hpp"
  7. #include <stdio.h>
  8. #include <iostream>
  9. #include <string>
  10. #include "platelocate.h"
  11. #include <android/log.h>
  12. #include "platelocate.h"
  13. using namespace easypr;
  14. using namespace std;
  15. using namespace cv;
  16. int m_GaussianBlurSize = 5;
  17. int m_MorphSizeWidth   = 17;
  18. int m_MorphSizeHeight  = 3;
  19. static const int DEFAULT_GAUSSIANBLUR_SIZE = 5;
  20. static const int SOBEL_SCALE = 1;
  21. static const int SOBEL_DELTA = 0;
  22. static const int SOBEL_DDEPTH = CV_16S;
  23. static const int SOBEL_X_WEIGHT = 1;
  24. static const int SOBEL_Y_WEIGHT = 0;
  25. static const int DEFAULT_MORPH_SIZE_WIDTH = 17;  // 17
  26. static const int DEFAULT_MORPH_SIZE_HEIGHT = 3;  // 3
  27. static const int WIDTH = 136;
  28. static const int HEIGHT = 36;
  29. static const int TYPE = CV_8UC3;
  30. static const int DEFAULT_VERIFY_MIN = 1;   // 3
  31. static const int DEFAULT_VERIFY_MAX = 24;  // 20
  32. static const int DEFAULT_ANGLE = 60;  // 30
  33. static const int DEFAULT_DEBUG = 1;
  34. #define  LOG_TAG    "platelocate_native"
  35. #define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
  36. #define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
  37. extern "C"
  38. char* jstring2str(JNIEnv* env, jstring jstr) {
  39.     char* rtn = NULL;
  40.     jclass clsstring = env->FindClass("java/lang/String");
  41.     jstring strencode = env->NewStringUTF("utf-8"); // "GB2312"
  42.     jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
  43.     jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);
  44.     jsize alen = env->GetArrayLength(barr);
  45.     jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
  46.     if (alen > 0) {
  47.         rtn = (char *)malloc(alen + 1);
  48.         memcpy(rtn, ba, alen);
  49.         rtn[alen] = 0;
  50.     }
  51.     env->ReleaseByteArrayElements(barr, ba, 0);
  52.     return rtn;
  53. }
  54. extern "C"
  55. jstring
  56. Java_com_example_gzh_myplatelocate_PlateRecognizer_stringFromJNI(
  57.         JNIEnv *env,
  58.         jobject /* this */) {
  59.     std::string hello = "Hello from C++ NDK 11111111111111";
  60.     LOGE("== Hello from C++ NDK 11111111111111");
  61.     return env->NewStringUTF(hello.c_str());
  62. }
  63. extern "C"
  64. JNIEXPORT jlong JNICALL
  65. Java_com_example_gzh_myplatelocate_PlateRecognizer_initPR(
  66.         JNIEnv *env, 
  67.         jobject) {
  68. //        const string *svm = (*env)->GetStringUTFChars(env, svmpath, 0);
  69. //        const string *ann = (*env)->GetStringUTFChars(env, annpath, 0);
  70.     CPlateLocate *pr = new CPlateLocate();
  71.     return (jlong)pr;
  72. }
  73. extern "C"
  74. JNIEXPORT jlong JNICALL
  75. Java_com_example_gzh_myplatelocate_PlateRecognizer_uninitPR(
  76.         JNIEnv *env,
  77.         jobject,
  78.         jlong recognizerPtr
  79.         )
  80. {
  81.     LOGE("== Java_com_example_gzh_myplatelocate_PlateRecognizer_uninitPR");
  82.     CPlateLocate *pr = (CPlateLocate *)recognizerPtr;
  83.     delete pr;
  84.     return 0;
  85. }
  86. #if 0
  87. extern "C"
  88. JNIEXPORT void JNICALL
  89. Java_com_example_gzh_myplatelocate_PlateRecognizer_mySobelOper
  90.         (JNIEnv * jenv,
  91.          jlong thiz,
  92.          jlong recognizerPtr,
  93.          jlong imageGray, jlong faces)
  94. {
  95.     Mat imgData_out;
  96.     Mat& mGr  = *(Mat*)imageGray;
  97.     Mat& mRgb = *(Mat*)faces;
  98.     LOGE("=1= Java_com_example_gzh_myplatelocate_PlateRecognizer_mySobelOper");
  99. LOGE("=2= mGr.cols=%d", mGr.cols);
  100. LOGE("=2= mGr.rows=%d", mGr.rows);
  101. LOGE("=2= mGr.dims=%d", mGr.dims);
  102. LOGE("=2= mGr.channels=%d", mGr.channels());
  103. //    cv:cvtColor(mGr, mRgb, CV_RGB2GRAY);
  104.     //mRgb = mRgb /255.0;
  105.     CPlateLocate *pr = (CPlateLocate *)recognizerPtr;
  106. #if 1
  107.     pr->sobelOper(mGr, imgData_out, m_GaussianBlurSize, m_MorphSizeWidth,m_MorphSizeHeight);
  108. #else
  109.     #if 1
  110.         pr->cvtgray(mGr, mRgb, CV_RGB2GRAY);
  111.     #else
  112.         cv:cvtColor(mGr, mRgb, CV_RGB2GRAY);
  113.     #endif
  114. #endif
  115. LOGE("=2= imgData_out.cols=%d", imgData_out.cols);
  116. LOGE("=2= imgData_out.rows=%d", imgData_out.rows);
  117. imgData_out.dims = 0;
  118. LOGE("=2= imgData_out.dims=%d", imgData_out.dims);
  119. LOGE("=2= imgData_out.channels=%d", imgData_out.channels());
  120. // imgData_out = imgData_out / 255.0;
  121. //   imgData_out.copyTo(*hist);
  122.     LOGE("=3= imgData_outJava_com_example_gzh_myplatelocate_PlateRecognizer_mySobelOper");
  123. }
  124. #else
  125. extern "C"
  126. JNIEXPORT void JNICALL
  127. Java_com_example_gzh_myplatelocate_PlateRecognizer_mySobelOper
  128.         (JNIEnv * jenv,
  129.          jlong thiz,
  130.          jlong recognizerPtr,
  131.          jlong imageGray, jlong faces)
  132. {
  133.     Mat imgData;
  134.     Mat imgData_out;
  135.     Mat *hist = new Mat();
  136.     Mat& mGr  = *(Mat*)imageGray;
  137.     Mat& mRgb = *(Mat*)faces;
  138.   //  hist = &imgData_out;
  139.     LOGE("=1= Java_com_example_gzh_myplatelocate_PlateRecognizer_mySobelOper");
  140.     LOGE("=2= mGr.cols=%d", mGr.cols);
  141.     LOGE("=2= mGr.rows=%d", mGr.rows);
  142.     LOGE("=2= mGr.dims=%d", mGr.dims);
  143.     LOGE("=2= mGr.channels=%d", mGr.channels());
  144. //    cv:cvtColor(mGr, mRgb, CV_RGB2GRAY);
  145.     //mRgb = mRgb /255.0;
  146.    // CPlateLocate *pr = (CPlateLocate *)recognizerPtr;
  147.    // pr->sobelOper(mGr, imgData_out, m_GaussianBlurSize, m_MorphSizeWidth,m_MorphSizeHeight);
  148.     Mat mat_blur;
  149.     LOGE("=1= sobelOper");
  150.     mat_blur = mGr.clone();
  151.     GaussianBlur(mGr, mat_blur, Size(m_GaussianBlurSize, m_GaussianBlurSize), 0, 0, BORDER_DEFAULT);
  152.     LOGE("=2= sobelOper mat_blur.channels()=%d", mat_blur.channels());
  153.     Mat mat_gray;
  154.     if (mat_blur.channels() == 3 || mat_blur.channels() == 4)
  155.         cvtColor(mat_blur, mat_gray, CV_RGB2GRAY);
  156.     else if(mat_blur.channels() == 42)
  157.     {
  158.         mat_blur.convertTo(mat_gray, SOBEL_DDEPTH);
  159.     }
  160.     else
  161.         mat_gray = mat_blur;
  162.     LOGE("=3= sobelOper");
  163.     int scale = SOBEL_SCALE;
  164.     int delta = SOBEL_DELTA;
  165.     int ddepth = SOBEL_DDEPTH;
  166.     Mat grad_x, grad_y;
  167.     Mat abs_grad_x, abs_grad_y;
  168.     LOGE("=444= sobelOper");
  169. #if 1
  170.     Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
  171.     convertScaleAbs(grad_x, abs_grad_x);
  172.     LOGE("=5= sobelOper");
  173.     Mat grad;
  174.     addWeighted(abs_grad_x, SOBEL_X_WEIGHT, 0, 0, 0, grad);
  175.     Mat mat_threshold;
  176.     double otsu_thresh_val = threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
  177.     LOGE("=6= sobelOper");
  178.     Mat element = getStructuringElement(MORPH_RECT, Size(m_MorphSizeWidth, m_MorphSizeHeight));
  179.     morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element);
  180.     mRgb = mat_threshold;
  181. #else
  182.     mRgb = mat_gray;
  183. #endif
  184.     LOGE("=71= sobelOper");
  185.    // faces = (jlong)hist;
  186.     LOGE("=3= imgData_outJava_com_example_gzh_myplatelocate_PlateRecognizer_mySobelOper");
  187. }
  188. #endif
  189. extern "C"
  190. JNIEXPORT void JNICALL
  191. Java_com_example_gzh_myplatelocate_PlateRecognizer_myCvtColor
  192.         (JNIEnv * jenv,
  193.          jlong thiz,
  194.          jlong imageGray, jlong faces)
  195. {
  196.     Mat imgData;
  197.     Mat imgData_out;
  198.     Mat *hist = new Mat();
  199.     imgData = *((Mat*)imageGray);
  200.     Mat& mGr  = *(Mat*)imageGray;
  201.     Mat& mRgb = *(Mat*)faces;
  202.     LOGE("== Java_com_example_gzh_myplatelocate_PlateRecognizer_myCvtColor");
  203.     LOGE("=myCvtColor= mGr.channels=%d", mGr.channels());
  204.     cv:cvtColor(mGr, mRgb, CV_RGB2GRAY);
  205.    // mRgb = mRgb /255.0;
  206.     LOGE("== Java_com_example_gzh_myplatelocate_PlateRecognizer_myCvtColor");
  207. }
  208. extern "C"
  209. JNIEXPORT jintArray JNICALL
  210. Java_com_example_gzh_myplatelocate_PlateRecognizer_getGrayImage(
  211.                 JNIEnv *env,
  212.                 jobject /* this */,
  213.                 jintArray pixels_,
  214.                 jint w,
  215.                 jint h
  216.                 ) {
  217.     jint *pixels = env->GetIntArrayElements(pixels_, NULL);
  218.     // TODO
  219.     if(pixels==NULL){
  220.         return NULL;
  221.     }
  222.     cv::Mat imgData(h, w, CV_8UC4, pixels);
  223.     uchar *ptr = imgData.ptr(0);
  224.     for (int i = 0; i < w * h; i++) {
  225.         int grayScale = (int) (ptr[4 * i + 2] * 0.299 + ptr[4 * i + 1] * 0.587
  226.                                + ptr[4 * i + 0] * 0.114);
  227.         ptr[4 * i + 1] = (uchar) grayScale;
  228.         ptr[4 * i + 2] = (uchar) grayScale;
  229.         ptr[4 * i + 0] = (uchar) grayScale;
  230.     }
  231.     int size = w * h;
  232.     jintArray result = env->NewIntArray(size);
  233.     env->SetIntArrayRegion(result, 0, size, pixels);
  234.     env->ReleaseIntArrayElements(pixels_, pixels, 0);
  235.     return result;
  236. }

复制代码

运行结果如下图:
 
附件是ubuntu系统的高斯模糊实现。


DragonCat liked
回复引用
  
Working

登陆 或者 注册