摘要:本文将带你了解Android应用开发之OpenCV On Android (Eclipse) 实例,希望本文对大家学Android有所帮助。
本文将带你了解Android应用开发之OpenCV On Android (Eclipse) 实例,希望本文对大家学Android有所帮助。
OpenCV On Android (Eclipse) 实例。
请自行下载openCV库 https://sourceforge.net/projects/opencvlibrary/
环境配置
第一步:Eclipse菜单->File->Import->Android->Existing Android Code Into Workspace(如果没此选项,请确保你的eclipse 上ADT是否配置正确),然后导入OpenCV Android SDK\ sdk\java这个项目。
为了防止误操作OpenCV库,建议勾选Copy project into workspace,将该库copy到你的工作文件夹。然后Finish,如果导入后出现报错,请将Project build Target设置为Android5.0以上(因为一般是Camera2报错,Camera2只存在于Android5.0+),具体方法是项目鼠标右键,选择Properties,然后点击Android,选择Android5.0以上的版本即可,然后OK,这里我选择的是6.0。
第二步:在你的项目右键也进入上图的页面,Library选择Add,添加OpenCV库(如下图),OK后,你的项目将可以使用OpenCV Java函数了。
抛弃OpenCV Manager:
安装一个额外的apk对用户来说非常不友好,但使用C/C++编程,对一些Java程序员又提高了实现难度,故我们应该想一个两全其美的方法,即帮助开发人员使用java快速开发,又给用户一良好体验。
思路:
Java库实际上只是对NDK库进行java封装,将so文件放在OpenCV Manager内,通过AIDL进行数据交流,并实现图像处理。
解决办法:
如果我们将OpenCV Manager里面的NDK库放到我们的应用里,不就能抛弃OpenCV Manager并实现图像处理了吗答案是YES,我们将OpenCV-android-sdk\sdk\native\libs\[架构]目录下(这里选择合适的架构,一般用armeabi即可)的libopencv_java3.so放在你的项目libs\[架构]目录(需自己手动创建)下,项目结构如图:
然后在你的MainActivity.java里面静态加载这个so库
public class MainActivity extends Activity implements OnClickListener {
private ImageView imageView;
private Bitmap bitmap;
private Button showBtn, processBtn;
private OpenCV_Java javaUtil = new OpenCV_Java(this); static{ System.loadLibrary("opencv_java3"); // 与"libs" 目录下的"armeabi"目录下的 "libopencv_java3.so"名字保持一致。低版本是 "opencv_java" } @Override protected void onCreate(Bundle savedInstanceState) { ......下面内容不变
MainActivity 完整代码:
package com.example.opencvdemo02;
import java.io.File;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import com.liushu.SearchFiles.SearchFiles;
import com.liushu.ShowPicture.ShowPicture;
import com.liushu.ocr.Train;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
String TAG="MainActivity";
ShowPicture mShowPicture;
ImageView imageView;
Button showBtn,processBtn,GetFileListButton;
SearchFiles mSearchFiles;
int FileCount;
Bitmap bitmap;
private OpenCV_Java javaUtil = new OpenCV_Java(this);
Boolean IsProcess=false;
static{
System.loadLibrary("opencv_java");
// 与"libs" 目录下的"armeabi"目录下的 "libopencv_java3.so"名字保持一致。
//低版本是 "opencv_java"
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetFileListButton=(Button)findViewById(R.id.OpenFileButton);
GetFileListButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Log.i(TAG,"Click");
File parent_path = Environment.getExternalStorageDirectory();
/* mSearchFiles.baseDIR=parent_path + "/Images/";
mSearchFiles.fileName="*.jpg";
*/
mSearchFiles=new SearchFiles(parent_path + "/MyOCR/","*.bmp");
//images
FileCount=mSearchFiles.FileCount;
for(int i=0;i
Log.i(TAG,mSearchFiles.SearchedFileName[i]);
String FileTitle;
int Position=mSearchFiles.SearchedFileName[i].indexOf(".");
FileTitle=mSearchFiles.SearchedFileName[i].substring(0, Position);
Log.i(TAG,FileTitle);
Bitmap bitmap = BitmapFactory.decodeFile(mSearchFiles.SearchedFullFileName[i]);
}
}
});
Button OpenPicture= (Button) findViewById(R.id.OpenPictureButton);
OpenPicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。
intent.setType("image/*");
//intent.setType(“audio/*”); //选择音频
//intent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
//intent.setType(“video/*;image/*”);//同时选择视频和图片
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent,1);
// startActivityForResult(Intent.createChooser(intent, "请选择文件!"),1);
}
});
imageView = (ImageView) findViewById(R.id.imageView);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lena);
processBtn = (Button) findViewById(R.id.process);
processBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i(TAG,"Click");
if (bitmap != null) {//避免二次处理
if(IsProcess){
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lena);
imageView.setImageBitmap(bitmap);
IsProcess=false;
}
else{
javaUtil.toGary(bitmap);
imageView.setImageBitmap(bitmap);
IsProcess=true;
}
}
}
}
);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (!OpenCVLoader.initDebug()) {
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_11, this, javaUtil);
} else {
javaUtil.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
Log.i("onResume","OK");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {//是否选择,没选择就不会继续
Uri uri = data.getData();//得到uri,后面就是将uri转化成file的过程。
// Log.i(TAG,"Path"+uri.getPath());
String[] proj = {MediaStore.Images.Media.DATA};
Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor.getString(actual_image_column_index);
File file = new File(img_path);
String FileName=file.toString();
Toast.makeText(MainActivity.this, FileName, Toast.LENGTH_SHORT).show();
Log.i(TAG,FileName);
mShowPicture=new ShowPicture(MainActivity.this,javaUtil,imageView,FileName);
// Bitmap bitmap = BitmapFactory.decodeFile(FileName);
// mImageView.setImageBitmap(bitmap);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
*********************************
OpenCV_Java.jav
package com.example.opencvdemo02;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.Toast;
public class OpenCV_Java extends BaseLoaderCallback {
private boolean isInit = false;
private Context context;
public OpenCV_Java(Context context){
super(context);
this.context = context;
}
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
isInit = true;
break;
default:
isInit = false;
super.onManagerConnected(status);
break;
}
}
public void toGary(Bitmap bitmap){
if(isInit){
Mat mat = new Mat();
Utils.bitmapToMat(bitmap, mat);
Imgproc.cvtColor(mat, mat,Imgproc.COLOR_RGBA2GRAY );
Utils.matToBitmap(mat, bitmap);
}else{
Toast.makeText(context, "OpenCV init error", Toast.LENGTH_LONG).show();
}
}
}
*************************
*************************
SearchFiles.java:
package com.liushu.SearchFiles;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.os.Environment;
import android.util.Log;
public class SearchFiles {
public String baseDIR;
public String fileName;
private List resultList;
public String[] SearchedFileName;
public String[] SearchedFullFileName;
public int FileCount=0;
public static Boolean IsSearchSubFolder=false;
public SearchFiles(String Path,String FileName) {
// TODO Auto-generated constructor stub
baseDIR=Path;
fileName=FileName;
FileCount=SearchFiles();
}
public int SearchFiles(){
// 在此目录中找文件
File FoundFile;
/* File parent_path = Environment.getExternalStorageDirectory();
baseDIR = parent_path + "/Images/";
*/
// 找扩展名为txt的文件
// String fileName = "*.jpg";
String FileFullName;
resultList = new ArrayList();
findFiles(baseDIR, fileName,resultList);
FileCount = resultList.size();
if (resultList.size() == 0) {
System.out.println("No File Fount.");
} else {
SearchedFileName = new String[FileCount];
SearchedFullFileName = new String[FileCount];
System.out.println(FileCount);//显示查找结果。
for (int i = 0; i < resultList.size(); i++) {
// System.out.println(resultList.get(i));//显示查找结果。
FoundFile=(File)(resultList.get(i));
FileFullName=FoundFile.getAbsolutePath();
SearchedFullFileName[i]=FileFullName;
// System.out.println(SearchedFullFileName[i]);
SearchedFileName[i]=FoundFile.getName();
}
System.out.println("Finish Read");//显示查找结果。
}
return FileCount;
}
private static void findFiles(String baseDirName, String targetFileName, List fileList) {
File baseDir = new File(baseDirName); // 创建一个File对象
if (!baseDir.exists() || !baseDir.isDirectory()) { // 判断目录是否存在
System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");
return;
}
//判断目录是否存在
File tempFile;
File[] files = baseDir.listFiles();
Log.i("findFiles",baseDir.getAbsolutePath());
if(files==null){
Log.i("findFiles","No files");
return;
}
// Log.i("findFiles",baseDir.getAbsolutePath()+" "+files.length);
String tempName = null;
for (int i = 0; i < files.length; i++) {
tempFile = files[i];
if(tempFile.isDirectory() && IsSearchSubFolder){
findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);
}else if(tempFile.isFile()){
tempName = tempFile.getName();
if(wildcardMatch(targetFileName, tempName)){
// 匹配成功,将文件名添加到结果集
fileList.add(tempFile.getAbsoluteFile());
}
}
}
}
/**
* 通配符匹配
* @param pattern 通配符模式
* @param str 待匹配的字符串
* @return 匹配成功则返回true,否则返回false
*/
private static boolean wildcardMatch(String pattern, String str) {
int patternLength = pattern.length();
int strLength = str.length();
int strIndex = 0;
char ch;
for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
ch = pattern.charAt(patternIndex);
if (ch == '*') {
//通配符星号*表示可以匹配任意多个字符
while (strIndex < strLength) {
if (wildcardMatch(pattern.substring(patternIndex + 1),
str.substring(strIndex))) {
return true;
}
strIndex++;
}
} else if (ch == '') {
//通配符问号表示匹配任意一个字符
strIndex++;
if (strIndex > strLength) {
//表示str中已经没有字符匹配了。
return false;
}
} else {
if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) {
return false;
}
strIndex++;
}
}
return (strIndex == strLength);
}
}
************************
*********ShowPicture.java***************
package com.liushu.ShowPicture;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import com.example.opencvdemo02.OpenCV_Java;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.Log;
import android.view.DragEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ZoomControls;
public class ShowPicture {
Bitmap bitmap;
Bitmap ShowBitmap,ScaledBitmap,FinalBitmap;
ImageView mImageView;
ZoomControls mZoomContorl;
int ImageWidth;
int ImageHeight;
int ImageViewWidth,ImageViewHeight;
double ScaleWidth,ScaleHeight,Scale=1;
int mScaleMinus=1,mScalePlus=1;
String TAG="ShowPicture";
boolean IsTouchDown=false,IsCrop=false;
int FirstX,FirstY,SecondX,SecondY;
int FontSize=60;
int ToolBarIntevalPixel=100;
Paint paintAll;
boolean IsDrawCropRect=false;
Activity mMainActivity;
private OpenCV_Java mjavaUtil;
/*
static{
System.loadLibrary("opencv_java");
}
*/
public ShowPicture(Activity MainActivity,OpenCV_Java javaUtil,ImageView myImageView,String ImagePath) {
// TODO Auto-generated constructor stub
Log.i(TAG,"loadLibrary ImageProc ");
mMainActivity=MainActivity;
mjavaUtil=javaUtil;
mImageView=myImageView;
ImageViewWidth=myImageView.getWidth();
ImageViewHeight=myImageView.getHeight();
FinalBitmap=Bitmap.createBitmap(ImageViewWidth, ImageViewHeight, Bitmap.Config.ARGB_8888);
CreatePaint();
bitmap = BitmapFactory.decodeFile(ImagePath);
javaUtil.toGary(bitmap);
bitmap=TwoValue(bitmap);
ImageWidth=bitmap.getWidth();
ImageHeight=bitmap.getHeight();
ScaleWidth=ImageViewWidth/ImageWidth;
ScaleHeight=ImageViewHeight/ImageHeight;
if(ScaleWidth<1 ||ScaleHeight<1){
//裁剪图片
ShowBitmap=CropBitmap(bitmap,ImageWidth,ImageHeight,ImageViewWidth,ImageViewHeight);
}else{
ShowBitmap=bitmap;
}
DrawFinalImage();
mImageView.setOnTouchListener(new ImageView.OnTouchListener() {
@Override public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int touch_X = (int) event.getX(); int touch_Y = (int) event.getY();
int w=v.getWidth(); int h=v.getHeight();
int ShowImageW=ShowBitmap.getWidth(),ShowImageH=ShowBitmap.getHeight();
Log.i("onTouch",touch_X+","+touch_Y);
switch (event.getAction()) {
case KeyEvent.ACTION_UP:
{
//松开事件发生后执行代码的区域
ActionOn(touch_X,touch_Y);
IsTouchDown=false;
break;
}
case KeyEvent.ACTION_DOWN:
{
// 按住事件发生后执行代码的区域
FirstX=touch_X;FirstY=touch_Y;
break;
}
default:
// Log.i("onTouch","Moving "+event.getAction()+","+touch_X+","+touch_Y);
if(IsCrop){
SecondX=touch_X;SecondY=touch_Y;
/* Bitmap bmp=Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas=new Canvas(bmp);
Paint paintAll=new Paint();
paintAll.setAlpha(255);//不透明度//完全不透明
paintAll.setAntiAlias(true);
paintAll.setColor(Color.rgb(0,0,0));//黑色//默认就是黑色
paintAll.setStyle(Paint.Style.FILL);
canvas.drawBitmap(ShowBitmap, (w-ShowImageW)/2, (h-ShowImageH)/2, paintAll);
paintAll.setStyle(Paint.Style.STROKE);
canvas.drawRect(FirstX, FirstY, SecondX, SecondY, paintAll);
*/
IsDrawCropRect=true;
DrawFinalImage();
// IsCrop=false;
// IsDrawCropRect=false;
}
break;
}
/* IsTouchDown=!IsTouchDown;
if(IsTouchDown){
FirstX=touch_X;FirstY=touch_Y;
}else{
}
*/
//
return true;
}
});
}
private void DrawFinalImage(){
int ShowImageW=ShowBitmap.getWidth(),ShowImageH=ShowBitmap.getHeight();
FinalBitmap=Bitmap.createBitmap(ImageViewWidth, ImageViewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas=new Canvas(FinalBitmap);
canvas.drawBitmap(ShowBitmap, (ImageViewWidth-ShowImageW)/2, (ImageViewHeight-ShowImageH)/2, paintAll);
// Log.i("DrawFinalImage","开始画顶部工具栏");
Mat ShowMat=new Mat(), FinalRectMat=new Mat(),MyRectMat=new Mat();
Mat MyRectMat2=new Mat(FontSize,ImageViewWidth,CvType.CV_8UC3);
MyRectMat2.ones(FontSize,ImageViewWidth,CvType.CV_8UC3);
Size mySize=new Size(ImageViewWidth,FontSize);
Point myPoint=new Point(ImageViewWidth/2.0,FontSize/2.0);
Scalar myScalar=new Scalar(255,255,255),myScalar2=new Scalar(0,0,0);
Utils.bitmapToMat(FinalBitmap, ShowMat);
//转成CV_8UC3格式
Imgproc.cvtColor(ShowMat, ShowMat, Imgproc.COLOR_RGBA2RGB);
// Imgproc.cvtColor(ShowMat, ShowMat, CvType.CV_8UC3);
myPoint.x=ImageViewWidth/2.0;
myPoint.y=FontSize/2.0;
Imgproc.getRectSubPix(ShowMat,mySize,myPoint,MyRectMat);
// Log.i("DrawFinalImage","开始画顶部工具栏");
myPoint=new Point(FontSize/2, FontSize/2);
// Log.i("DrawFinalImage","开始画顶部工具栏");
Core.addWeighted(MyRectMat,0.5,MyRectMat2,0.3,0,FinalRectMat);
Log.i("DrawFinalImage","开始画顶部工具栏");
int LineThickness=5;
int [] baseline = new int[1];
int font_face =Core.FONT_HERSHEY_SIMPLEX;
int font_scale=1;
Size text_size = Core.getTextSize("-", font_face, font_scale, LineThickness, baseline);
Core.circle(FinalRectMat,myPoint,FontSize/2-LineThickness,myScalar,LineThickness,8,0);
Point Point0=new Point(FontSize/2-text_size.width/2,FontSize/2+text_size.height/2);
Core.putText(FinalRectMat, "-", Point0, font_face, font_scale, myScalar, LineThickness);
Point0=new Point(ToolBarIntevalPixel+FontSize/2, FontSize/2);
Core.circle(FinalRectMat,Point0,FontSize/2-LineThickness,myScalar,LineThickness,8,0);
text_size = Core.getTextSize("+", font_face, font_scale, LineThickness, baseline);
Point0=new Point(ToolBarIntevalPixel+FontSize/2-text_size.width/2, FontSize/2+text_size.height/2);
Core.putText(FinalRectMat, "+", Point0, Core.FONT_HERSHEY_SIMPLEX, font_scale, myScalar, LineThickness);
Point0=new Point(ToolBarIntevalPixel*2, 0);
Point Point1=new Point(ToolBarIntevalPixel*2+FontSize, FontSize);
Core.rectangle(FinalRectMat, Point0, Point1, myScalar, LineThickness);
Log.i(TAG,ImageViewWidth+","+ImageViewHeight+" "+ShowMat.cols()+","+ShowMat.rows());
Imgproc.copyMakeBorder(FinalRectMat,FinalRectMat,0,ImageViewHeight-FinalRectMat.rows(),0,0, Imgproc.BORDER_CONSTANT,myScalar2);
FinalRectMat.copyTo(ShowMat,FinalRectMat);
//转成CV_8UC4格式
Imgproc.cvtColor(ShowMat, ShowMat,Imgproc.COLOR_RGB2RGBA);
Log.i(TAG,ImageViewWidth+","+ImageViewHeight+" "+ShowMat.cols()+","+ShowMat.rows());
Utils.matToBitmap(ShowMat, FinalBitmap);
/*
canvas.drawText("--",paintAll.getStrokeWidth(),FontSize-paintAll.getStrokeWidth(),paintAll);
canvas.drawCircle(FontSize/2, FontSize/2, FontSize/2, paintAll);
canvas.drawText("+",ToolBarIntevalPixel+paintAll.getStrokeWidth(),FontSize-paintAll.getStrokeWidth(),paintAll);
canvas.drawCircle(ToolBarIntevalPixel+FontSize/2, FontSize/2, FontSize/2, paintAll);
canvas.drawRect(ToolBarIntevalPixel*2, 0, ToolBarIntevalPixel*2+FontSize, FontSize, paintAll);
*/
if(IsDrawCropRect){
canvas.drawRect(FirstX, FirstY, SecondX, SecondY, paintAll);
}
//****
mImageView.setImageBitmap(FinalBitmap);
}
private void CreatePaint(){
paintAll=new Paint();
paintAll.setAlpha(255);//不透明度//完全不透明
paintAll.setAntiAlias(true);
paintAll.setColor(Color.rgb(255,255,255));//黑色//默认就是黑色
// paintAll.setStyle(Paint.Style.FILL);
paintAll.setStyle(Paint.Style.STROKE);
paintAll.setStrokeWidth(5);
paintAll.setTextSize(FontSize);
}
private void ActionOn(int X,int Y){
if(X if(FirstX IsCrop=false;
ZoomOut();
return;
}
}
if(XToolBarIntevalPixel && Y if(FirstXToolBarIntevalPixel && FirstY IsCrop=false;
ZoomIn();
return;
}
}
if(XToolBarIntevalPixel*2 && Y if(FirstXToolBarIntevalPixel*2 && FirstY IsCrop=true;
return;
}else{
IsCrop=false;
}
}
if(IsCrop){
Toast.makeText(mMainActivity, "Crop the picture", Toast.LENGTH_SHORT).show();
Matrix outputMatrix = new Matrix();
outputMatrix.setScale(1, 1);
int Left,Top,Right,Bottom,CropWidth,CropHeight;
if(FirstX>SecondX){
Left=SecondX;
CropWidth=FirstX-SecondX;
}else{
Left=FirstX;
CropWidth=SecondX-FirstX;
}
if(FirstY>SecondY){
Top=SecondY;
CropHeight=FirstY-SecondY;
}else{
Top=FirstY;
CropHeight=SecondY-FirstY;
}
Bitmap CropImage= Bitmap.createBitmap(ShowBitmap,
Left, Top, CropWidth, CropHeight,
outputMatrix, false);
AnalysisSamplePicture(CropImage);
}
}
private Bitmap AnalysisSamplePicture(Bitmap CropImage){
return TwoValue(CropImage);
}
private Bitmap Gray(Bitmap bmp){
int width = bmp.getWidth();
int height = bmp.getHeight();
int[] data = new int[width * height];
bmp.getPixels(data, 0, width, 0, 0, width, height);
Bitmap resultImg = Bitmap.createBitmap(width, height, Config.ARGB_8888);
// resultImg.setPixels(result, 0, width, 0, 0, width, height);
Mat rgbMat = new Mat();
Mat grayMat = new Mat();
//获取lena彩色图像所对应的像素数据
Utils.bitmapToMat(bmp, rgbMat);
//将彩色图像数据转换为灰度图像数据并存储到grayMat中
Imgproc.cvtColor(rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);
//创建一个灰度图像
Bitmap grayBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Config.RGB_565);
//将矩阵grayMat转换为灰度图像
Utils.matToBitmap(grayMat, grayBmp);
return grayBmp;
}
private Bitmap TwoValue(Bitmap bmp){
Mat dstMat = new Mat(),BlackWhiteMat = new Mat(),grayMat= new Mat();
int nY20_thresh=96;
int blockSize = 25;
double constValue = 10;
Utils.bitmapToMat(bmp, grayMat); //24位 RGBA格式。
//转成CV_8UC3格式
Imgproc.cvtColor(grayMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
// String aa="";
// aa = grayMat.type()+"";
// Log.i(TAG, "Type:"+aa+ " Vs "+CvType.CV_8UC1+" "+CvType.CV_8UC3);
grayMat.convertTo(BlackWhiteMat, CvType.CV_8UC1);
// aa = BlackWhiteMat.type()+"";
// Log.i(TAG, "Type:"+aa+ " Vs "+CvType.CV_8UC1);
//type选THRESH_BINARY,大于阈值的设置为maxval(255),其它置0
// Imgproc.threshold(grayMat, dstMat, nY20_thresh, 255, Imgproc.THRESH_BINARY);
Imgproc.adaptiveThreshold(BlackWhiteMat, dstMat, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, blockSize, constValue);
Bitmap grayBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Config.RGB_565);
Utils.matToBitmap(dstMat, grayBmp);
return grayBmp;
}
private void ZoomOut(){
if(mScalePlus==1){
if(mScaleMinus<=4){
mScaleMinus*=2;
}else{
return;
}
}else if(mScalePlus>=2){
mScalePlus/=2;
mScaleMinus=1;
}else{
mScaleMinus=1;
mScaleMinus=1;
}
Bitmap ScaledBitmap=scaleMyBitmap(bitmap,ImageWidth*mScalePlus/mScaleMinus,ImageHeight*mScalePlus/mScaleMinus);
int CurrentImageWidth=ScaledBitmap.getWidth();
int CurrentImageHeight=ScaledBitmap.getHeight();
ScaleWidth=ImageViewWidth/CurrentImageWidth;
ScaleHeight=ImageViewHeight/CurrentImageHeight;
if(ScaleWidth<1 ||ScaleHeight<1){
//裁剪图片
ShowBitmap=CropBitmap(ScaledBitmap,CurrentImageWidth,CurrentImageHeight,ImageViewWidth,ImageViewHeight);
}else{
ShowBitmap=ScaledBitmap;
}
DrawFinalImage();
// mImageView.setImageBitmap(FinalBitmap);
}
private void ZoomIn(){
//放大
if(mScaleMinus==1){
if(mScalePlus<=2){
mScalePlus*=2;
}else{
return;
}
}else if(mScaleMinus>=2){
mScaleMinus/=2;
mScalePlus=1;
}else{
mScaleMinus=1;
mScaleMinus=1;
}
ScaledBitmap=scaleMyBitmap(bitmap,ImageWidth*mScalePlus/mScaleMinus,ImageHeight*mScalePlus/mScaleMinus);
int CurrentImageWidth=ScaledBitmap.getWidth();
int CurrentImageHeight=ScaledBitmap.getHeight();
ScaleWidth=ImageViewWidth/CurrentImageWidth;
ScaleHeight=ImageViewHeight/CurrentImageHeight;
Log.i(TAG,CurrentImageWidth+"*"+CurrentImageHeight);
if(ScaleWidth<1 ||ScaleHeight<1){
//裁剪图片
ShowBitmap=CropBitmap(ScaledBitmap,CurrentImageWidth,CurrentImageHeight,ImageViewWidth,ImageViewHeight);
}else{
ShowBitmap=ScaledBitmap;
}
DrawFinalImage();
// mImageView.setImageBitmap(FinalBitmap);
// mZoomContorl.bringToFront();
// mZoomContorl.show();
}
/**
* 从中心裁剪图片
* @param bitmap
* @param ImageWidth
* @param ImageHeight
* @param ImageViewWidth
* @param ImageViewHeight
* @return
*/
private Bitmap CropBitmap(Bitmap bitmap,int ImageWidth,int ImageHeight,int ImageViewWidth,int ImageViewHeight){
Bitmap CroppedBitmap = null;
int cropX=0,cropY=0;
Matrix outputMatrix = new Matrix();
outputMatrix.setScale(1, 1);
int cropWidth=ImageWidth;
if(ImageViewWidth cropX=(ImageWidth-ImageViewWidth)/2;
cropWidth=ImageViewWidth;
}
int cropHeight=ImageHeight;
if(ImageViewHeight cropY=(ImageHeight-ImageViewHeight)/2;
cropHeight=ImageViewHeight;
}
return Bitmap.createBitmap(bitmap,
cropX, cropY, cropWidth, cropHeight,
outputMatrix, false);
}
public Bitmap scaleMyBitmap(Bitmap bitmap, int nWidth,int nHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// // Log.i("Harrison", "nWidth="+nWidth+", nHeight"+nHeight);
float scaleWidth = ((float) nWidth)/width;
float scaleHeight = ((float)nHeight)/height;
// Log.i("scaleMyBitmap", width+","+ height);
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return resizedBitmap;
}
}
*********************************
***********activity_main.xml**********************
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.opencvdemo02.MainActivity" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/OpenFileButton"
android:layout_marginTop="30dp"
android:src="@drawable/lena" />
android:id="@+id/OpenFileButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/OpenPictureButton"
android:layout_alignBottom="@+id/OpenPictureButton"
android:layout_alignParentLeft="true"
android:text="Train" />
android:id="@+id/OpenPictureButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_toLeftOf="@+id/process"
android:text="OpenPicture" />
android:id="@+id/process"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/imageView"
android:layout_alignRight="@+id/imageView"
android:text="Process" />
**************************
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注移动开发之Android频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号