Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.shoppinghelper;
- import java.io.File;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.Locale;
- import org.opencv.android.BaseLoaderCallback;
- import org.opencv.android.LoaderCallbackInterface;
- import org.opencv.android.OpenCVLoader;
- import org.opencv.android.Utils;
- import org.opencv.core.Mat;
- import org.opencv.core.MatOfDMatch;
- import org.opencv.core.Size;
- import org.opencv.features2d.DMatch;
- import org.opencv.features2d.DescriptorMatcher;
- import org.opencv.highgui.Highgui;
- import org.opencv.imgproc.Imgproc;
- import android.support.v7.app.ActionBarActivity;
- import android.support.v7.app.ActionBar;
- import android.support.v4.app.Fragment;
- import android.content.Intent;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.net.Uri;
- import android.os.Bundle;
- import android.os.Environment;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.Toast;
- import android.os.Build;
- import android.provider.MediaStore;
- public class SiftActivity extends ActionBarActivity {
- //imageView on which the image will be displayed
- private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
- public static final int MEDIA_TYPE_IMAGE = 1;
- private static final String IMAGE_DIRECTORY_NAME = "OpenCV Demo";
- private Uri fileUri;
- private ImageView imgPreview;
- private Button btnCapturePicture;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this, mOpenCVCallBack))
- {
- Log.e("TEST", "Cannot connect to OpenCV Manager");
- }
- setContentView(R.layout.activity_sift);
- //setting banana listView activity
- // setBananaView();
- //setting tomato view activity
- // setTomatoView();
- //setting chicken view Activity
- // setChickenView();
- //algorithm
- }
- private void captureImage(){
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
- intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
- startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
- }
- public Uri getOutputMediaFileUri(int type) {
- return Uri.fromFile(getOutputMediaFile(type));
- }
- private static File getOutputMediaFile(int type){
- // External sdcard location
- File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
- if (!mediaStorageDir.exists()) {
- if (!mediaStorageDir.mkdirs()) {
- Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
- + IMAGE_DIRECTORY_NAME + " directory");
- return null;
- }
- }
- // Create a media file name
- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
- Locale.getDefault()).format(new Date());
- File mediaFile;
- if (type == MEDIA_TYPE_IMAGE) {
- mediaFile = new File(mediaStorageDir.getPath() + File.separator
- + "IMG_" + timeStamp + ".jpg");
- } else {
- return null;
- }
- return mediaFile;
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- // if the result is capturing Image
- if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
- if (resultCode == RESULT_OK) {
- // successfully captured the image
- // display it in image view
- previewCapturedImage();
- } else if (resultCode == RESULT_CANCELED) {
- // user cancelled Image capture
- Toast.makeText(getApplicationContext(),
- "User cancelled image capture", Toast.LENGTH_SHORT)
- .show();
- } else {
- // failed to capture image
- Toast.makeText(getApplicationContext(),
- "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
- .show();
- }
- }
- }
- private void previewCapturedImage() {
- try {
- imgPreview.setVisibility(View.VISIBLE);
- // bimatp factory
- BitmapFactory.Options options = new BitmapFactory.Options();
- // downsizing image as it throws OutOfMemory Exception for larger
- // images
- options.inSampleSize = 8;
- final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
- options);
- Mat m = new Mat();
- Utils.bitmapToMat(bitmap, m);
- Mat resizedImage = new Mat();
- Size newSize = new Size(200,200);
- Imgproc.resize(m, resizedImage, newSize);
- String[]filepaths = {"/storage/extSdCard/DCIM/Camera/pomidor.desc",
- "/storage/extSdCard/DCIM/Camera/banany.desc","/storage/extSdCard/DCIM/Camera/papryki.desc"};
- switch(Matching(resizedImage, filepaths, 0.8f)){
- case 0 :
- startActivity(new Intent(SiftActivity.this, Tomato.class));
- this.finish();
- break;
- case 1:
- startActivity(new Intent(SiftActivity.this, BananaActivity.class));
- this.finish();
- break;
- case 2 :
- startActivity(new Intent(SiftActivity.this, ChickenActivity.class));
- this.finish();
- break;
- }
- } catch (NullPointerException e) {
- e.printStackTrace();
- }
- }
- private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
- @Override
- public void onManagerConnected(int status) {
- switch (status) {
- case LoaderCallbackInterface.SUCCESS:
- {
- // This is the exact same stuff we had in onCreate earlier
- // We're just making sure that it'll only run if we successfully do the OpenCV setup.
- imgPreview = (ImageView) findViewById(R.id.siftDisplay);
- btnCapturePicture = (Button) findViewById(R.id.btnImageCapture);
- btnCapturePicture.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- captureImage();
- }
- });
- } break;
- default:
- {
- super.onManagerConnected(status);
- } break;
- }
- }
- };
- public static int Matching (Mat img, String[] descPaths, float ratio) {
- //utworzenie deskryptora sift dla zadanego obrazka (zdjecia)
- SiftExtractor sift1 = new SiftExtractor(img, 3);
- //Pobranie deskryptora (zmienic na private, dodac funkcje get
- Mat qDesc = sift1.descriptors;
- sift1 = null; //zwalniamy obiekt
- //tworzymy obiekt matchera poslugujacego sie algorytmem FLANN (z OpenCV)
- DescriptorMatcher dm = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
- //Lista dopasowan
- List<MatOfDMatch> matchesList = new ArrayList<MatOfDMatch>();
- //tablica pomocnicza z poj dopasowaniem
- DMatch [] dArr = new DMatch[2];
- int descCount = descPaths.length;
- Mat tmpDesc;
- //tablica przechowujaca ilosc dobrych dopasowan obrazu wzorcowego z kazdym z deskryptorow
- //z niej wybierana bedzie najwieksza ilsoc dopasown - dzieki temu wiadomo do ktorego deskryptora
- //dopasowano obrazek - indeks tablicy to indeks deskryptora w tablicy descPaths
- int [] goodMatchesCount = new int[descCount];
- //indeks elementu z maksimalna wartoscia, na pocz ustawiamy na 0 - klasyczny alg wyszukiw max
- int maxIdx = 0;
- try {
- //po wszystkich deskryptorach
- for (int i = 0; i < descCount; ++i) {
- //wczytujemy z pliku - w aplikacji rzeczywistej niedopuszczalne ciagle wczytywanie z pliku - nieoptymalne
- //ale nie mozna tego przechowywac w pamieci bo jeden deskryptor moze miec nawet kilka MB
- tmpDesc = SiftExtractor.ReadDescriptorFromFile(descPaths[i]);
- //dopasowanie algorytmem k-NN (w tym wyp. 2 najblizszych sasiadow) - patrz dokumentacja i internet
- dm.knnMatch(qDesc, tmpDesc, matchesList, 2);
- //po wszystkich dopasowaniach
- for (MatOfDMatch match : matchesList) {
- //pobranie do tabl pomocniczej
- dArr = match.toArray();
- //spr stosunku odleglosci dopasowan - patrz praca
- if (dArr[0].distance/dArr[1].distance < ratio)
- //mniejszy niz ratio, inkrementujemy licznik
- goodMatchesCount[i]++;
- }
- //jesli wart biez el tablicy wieksza od max, przypisujemy indeks noweg maxa
- if (goodMatchesCount[i] > goodMatchesCount[maxIdx]) maxIdx = i;
- }
- //czyscimy liste do ponownego uzycia
- matchesList.clear();
- }
- catch(IOException e) {
- //exception handling
- e.printStackTrace();
- }
- return maxIdx; //zwracamy znaleziony max
- }
- /*
- /**
- * Method for starting ChickenActivity with the use of the button's click
- */
- private void setChickenView() {
- //Button btn3 = (Button)findViewById(R.id.startChickenActivity);
- // btn3.setOnClickListener(new View.OnClickListener() {
- // @Override
- // public void onClick(View v) {
- startActivity(new Intent(SiftActivity.this, ChickenActivity.class));
- // }
- // });
- }
- /**
- * Method for starting TomatoActivity with the use of the button's click
- */
- private void setTomatoView() {
- //Button btn2 = (Button)findViewById(R.id.startTomatoActivity);
- //btn2.setOnClickListener(new View.OnClickListener() {
- // @Override
- // public void onClick(View v) {
- startActivity(new Intent(SiftActivity.this, Tomato.class));
- // }
- // });
- }
- /**
- * Method for starting BananaActivity with the use of the button's click
- */
- private void setBananaView() {
- // Button btn = (Button)findViewById(R.id.startBananaActivity);
- // btn.setOnClickListener(new View.OnClickListener() {
- // @Override
- // public void onClick(View v) {
- // startActivity(new Intent(SiftActivity.this, BananaActivity.class));
- }
- // });
- //}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement