android studio 3.4 与 opencv-4.1.0-android-sdk——简单处理图片

4 篇文章 0 订阅

基于上一篇  android studio 3.4 与 opencv-4.1.0-android-sdk  初步调用,这篇实现调用Mat 处理静态图片

1.请先参考上一篇文章

2.添加资源修改布局  -- pic_test.png 自己随便找一张图片

内容:

----------------------------Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="原图:"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:src="@mipmap/pic_test"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt" />


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="处理后的图:"
        app:layout_constraintBottom_toTopOf="@+id/img2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/img"
        app:layout_constraintVertical_bias="0.142" />

    <ImageView
        android:id="@+id/img2"
        android:layout_width="404dp"
        android:layout_height="280dp"
        android:layout_marginStart="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent" />


</android.support.constraint.ConstraintLayout>

3.修改cpp代码

内容:

-------------------------------com_example_myapplication_test.h


/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_myapplication_test */

#ifndef _Included_com_example_myapplication_test
#define _Included_com_example_myapplication_test
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_example_myapplication_test
 * Method:    opencvVer
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_example_myapplication_test_opencvVer
  (JNIEnv *, jclass, jstring);

/*
 * Class:     com_example_myapplication_test
 * Method:    img2gray
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jintArray JNICALL  Java_com_example_myapplication_test_img2gray(
        JNIEnv *env, jclass obj, jintArray buf, int w, int h);

#ifdef __cplusplus
}
#endif
#endif


-------------------------------com_example_myapplication_test.cpp




#include "com_example_myapplication_test.h"

#include <opencv2/opencv.hpp>

using namespace cv;

#include <Android/log.h>
#include <Android/asset_manager.h>
#include <Android/asset_manager_jni.h>

#define TAG "cn.linjk.opencvtest.jni"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__)
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__)

extern "C"
JNIEXPORT jstring JNICALL Java_com_example_myapplication_test_opencvVer
    (JNIEnv *env , jclass objClass, jstring imgFilePath) {

        LOGI("OpenCV version: %s", CV_VERSION);
        return imgFilePath;
    }



extern "C"
JNIEXPORT jintArray JNICALL Java_com_example_myapplication_test_img2gray(
        JNIEnv *env, jclass obj, jintArray buf, int w, int h) {

      jint *cbuf;
        cbuf = env->GetIntArrayElements(buf, JNI_FALSE );
        if (cbuf == NULL) {
            return 0;
        }

        Mat imgData(h, w, CV_8UC4, (unsigned char *) cbuf);

        uchar* ptr = imgData.ptr(0);
        for(int i = 0; i < w*h; i ++){
            //计算公式:Y(亮度) = 0.299*R + 0.587*G + 0.114*B
            //对于一个int四字节,其彩色值存储方式为:BGRA
            int grayScale = (int)(ptr[4*i+2]*0.299 + ptr[4*i+1]*0.587 + ptr[4*i+0]*0.114);
            ptr[4*i+1] = grayScale;
            ptr[4*i+2] = grayScale;
            ptr[4*i+0] = grayScale;
        }

        int size = w * h;
        jintArray result = env->NewIntArray(size);
        env->SetIntArrayRegion(result, 0, size, cbuf);
        env->ReleaseIntArrayElements(buf, cbuf, 0);
        return result;
     // return nullptr;
    }

 

4.修改java代码

内容:

-----------------------test.java
package com.example.myapplication; 
public class test {
    static {
        try {
            System.loadLibrary("test_lib");
            System.out.println("load:");
        } catch (Throwable e) {
            System.out.println("err :"+e.toString());

        }

    }

    public static  native String opencvVer(String str);
    public static native int[] img2gray(int[] buf, int w, int h);

}

-----------------------------MainActivity
package com.example.myapplication;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        test.opencvVer("sdf");

        Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(
                R.mipmap.pic_test)).getBitmap();
        int w = bitmap.getWidth(), h = bitmap.getHeight();
        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);
        int [] resultPixes=test.img2gray(pix,w,h);
        Bitmap result = Bitmap.createBitmap(w,h, Bitmap.Config.RGB_565);
        result.setPixels(resultPixes, 0, w, 0, 0,w, h);

        ImageView img = (ImageView)findViewById(R.id.img2);
        img.setImageBitmap(result);
    }
}

 

5.修改build.gradle 和 CMakelists.txt

内容:

-------------------build.gradle

      sourceSets {
            main {
                // let gradle pack the shared library into apk

                jniLibs.srcDirs = ['../native/libs']
            }
        }

    externalNativeBuild {
        cmake {
            path file('CMakeLists.txt')
        }
    }



----------------------CMakelists.txt



# For more information about using CMake with Android Studio, read the 
# documentation: https://d.android.com/studio/projects/add-native-code.html 
# Sets the minimum version of CMake required to build the native library. 

cmake_minimum_required(VERSION 3.4.1)

set(CMAKE_VERBOSE_MAKEFILE on)  #希望查看更多信息 

# Creates and names a library, sets it as either STATIC 
# or SHARED, and provides the relative paths to its source code. 
# You can define multiple libraries, and CMake builds them for you. 
# Gradle automatically packages shared libraries with your APK. 
 

# set()用来设置一个路径全局变量 distribution_DIR
#opencv
set(distribution_DIR ${CMAKE_SOURCE_DIR}/../native)

#test_lib
aux_source_directory(src/main/cpp MainCPP) 

add_library( test_lib #.so库名 可自定义
              SHARED
              ${MainCPP} ) #源文件所在目录

 #链接第三方库的头文件
target_include_directories(test_lib PRIVATE
                           ${distribution_DIR}/jni/include)

# 创建一个动态库 lib_two 直接引用lib_so.so
add_library(opencv_java4 SHARED IMPORTED)
set_target_properties(opencv_java4 PROPERTIES IMPORTED_LOCATION
    ${distribution_DIR}/libs/${ANDROID_ABI}/libopencv_java4.so)

find_library( # Sets the name of the path variable. 
              log-lib 
              # Specifies the name of the NDK library that 
              # you want CMake to locate. 
              log )
 

# Specifies libraries CMake should link to your target library. You 
# can link multiple libraries, such as libraries you define in this 
# build script, prebuilt third-party libraries, or system libraries. 

target_link_libraries( # Specifies the target library. 
                       test_lib #.so库名 可自定义 
                       # Links the target library to the log library 
                       # included in the NDK.
 
                       ${log-lib} )



#把所有库文件都引入工程
target_link_libraries(
                       test_lib
                       opencv_java4
                       ${log-lib} )

6.调试与运行

 

准后附上参考资料:

----主
Android 接入 OpenCV库的三种方式   --https://www.cnblogs.com/xiaoxiaoqingyi/p/6676096.html

Android studio关于Cmake的使用(第三章·引用第三方库文件)  ---https://blog.csdn.net/ma598214297/article/details/78387847    

--次
使用Android Studio创建OpenCV 4.1.0 项目    ----https://blog.csdn.net/userhu2012/article/details/89522851

Android 接入 OpenCV4.1.0 sdk流程    ----https://blog.csdn.net/WangRain1/article/details/89491258

编译OpenCV for Android   ---https://blog.csdn.net/hjwang1/article/details/89112624  https://blog.csdn.net/minger1202/article/details/71429708

 使用OpenCV3.4.1库实现人脸检测     ---https://blog.csdn.net/AndrExpert/article/details/78992490

cmake使用总结(转)---工程主目录CMakeList文件编写  ---https://www.cnblogs.com/Free-Thinker/p/6163315.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值