Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2014
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.49 KB | None | 0 0
  1. package com.example.shoppinghelper;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.List;
  9. import java.util.Locale;
  10.  
  11. import org.opencv.android.BaseLoaderCallback;
  12. import org.opencv.android.LoaderCallbackInterface;
  13. import org.opencv.android.OpenCVLoader;
  14. import org.opencv.android.Utils;
  15. import org.opencv.core.Mat;
  16. import org.opencv.core.MatOfDMatch;
  17. import org.opencv.core.Size;
  18. import org.opencv.features2d.DMatch;
  19. import org.opencv.features2d.DescriptorMatcher;
  20. import org.opencv.highgui.Highgui;
  21. import org.opencv.imgproc.Imgproc;
  22.  
  23.  
  24. import android.support.v7.app.ActionBarActivity;
  25. import android.support.v7.app.ActionBar;
  26. import android.support.v4.app.Fragment;
  27. import android.content.Intent;
  28. import android.graphics.Bitmap;
  29. import android.graphics.BitmapFactory;
  30. import android.net.Uri;
  31. import android.os.Bundle;
  32. import android.os.Environment;
  33. import android.util.Log;
  34. import android.view.LayoutInflater;
  35. import android.view.Menu;
  36. import android.view.MenuItem;
  37. import android.view.View;
  38. import android.view.ViewGroup;
  39. import android.widget.Button;
  40. import android.widget.ImageView;
  41. import android.widget.Toast;
  42. import android.os.Build;
  43. import android.provider.MediaStore;
  44.  
  45. public class SiftActivity extends ActionBarActivity {
  46. //imageView on which the image will be displayed
  47. private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
  48. public static final int MEDIA_TYPE_IMAGE = 1;
  49. private static final String IMAGE_DIRECTORY_NAME = "OpenCV Demo";
  50. private Uri fileUri;
  51. private ImageView imgPreview;
  52. private Button btnCapturePicture;
  53.  
  54. @Override
  55. protected void onCreate(Bundle savedInstanceState) {
  56. super.onCreate(savedInstanceState);
  57. if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this, mOpenCVCallBack))
  58. {
  59. Log.e("TEST", "Cannot connect to OpenCV Manager");
  60. }
  61. setContentView(R.layout.activity_sift);
  62. //setting banana listView activity
  63. // setBananaView();
  64. //setting tomato view activity
  65. // setTomatoView();
  66. //setting chicken view Activity
  67. // setChickenView();
  68. //algorithm
  69. }
  70. private void captureImage(){
  71. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  72. fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
  73.  
  74. intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
  75. startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
  76. }
  77. public Uri getOutputMediaFileUri(int type) {
  78. return Uri.fromFile(getOutputMediaFile(type));
  79. }
  80. private static File getOutputMediaFile(int type){
  81. // External sdcard location
  82. File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
  83.  
  84. if (!mediaStorageDir.exists()) {
  85. if (!mediaStorageDir.mkdirs()) {
  86. Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
  87. + IMAGE_DIRECTORY_NAME + " directory");
  88. return null;
  89. }
  90. }
  91. // Create a media file name
  92. String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
  93. Locale.getDefault()).format(new Date());
  94. File mediaFile;
  95. if (type == MEDIA_TYPE_IMAGE) {
  96. mediaFile = new File(mediaStorageDir.getPath() + File.separator
  97. + "IMG_" + timeStamp + ".jpg");
  98. } else {
  99. return null;
  100. }
  101.  
  102. return mediaFile;
  103. }
  104. @Override
  105. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  106. // if the result is capturing Image
  107. if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
  108. if (resultCode == RESULT_OK) {
  109. // successfully captured the image
  110. // display it in image view
  111. previewCapturedImage();
  112. } else if (resultCode == RESULT_CANCELED) {
  113. // user cancelled Image capture
  114. Toast.makeText(getApplicationContext(),
  115. "User cancelled image capture", Toast.LENGTH_SHORT)
  116. .show();
  117. } else {
  118. // failed to capture image
  119. Toast.makeText(getApplicationContext(),
  120. "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
  121. .show();
  122. }
  123. }
  124. }
  125. private void previewCapturedImage() {
  126. try {
  127. imgPreview.setVisibility(View.VISIBLE);
  128.  
  129. // bimatp factory
  130. BitmapFactory.Options options = new BitmapFactory.Options();
  131.  
  132. // downsizing image as it throws OutOfMemory Exception for larger
  133. // images
  134. options.inSampleSize = 8;
  135.  
  136. final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
  137. options);
  138.  
  139. Mat m = new Mat();
  140. Utils.bitmapToMat(bitmap, m);
  141. Mat resizedImage = new Mat();
  142. Size newSize = new Size(200,200);
  143. Imgproc.resize(m, resizedImage, newSize);
  144.  
  145.  
  146.  
  147. String[]filepaths = {"/storage/extSdCard/DCIM/Camera/pomidor.desc",
  148. "/storage/extSdCard/DCIM/Camera/banany.desc","/storage/extSdCard/DCIM/Camera/papryki.desc"};
  149. switch(Matching(resizedImage, filepaths, 0.8f)){
  150. case 0 :
  151. startActivity(new Intent(SiftActivity.this, Tomato.class));
  152. this.finish();
  153. break;
  154. case 1:
  155. startActivity(new Intent(SiftActivity.this, BananaActivity.class));
  156. this.finish();
  157. break;
  158. case 2 :
  159. startActivity(new Intent(SiftActivity.this, ChickenActivity.class));
  160. this.finish();
  161. break;
  162. }
  163. } catch (NullPointerException e) {
  164. e.printStackTrace();
  165. }
  166. }
  167. private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
  168. @Override
  169. public void onManagerConnected(int status) {
  170. switch (status) {
  171. case LoaderCallbackInterface.SUCCESS:
  172. {
  173. // This is the exact same stuff we had in onCreate earlier
  174. // We're just making sure that it'll only run if we successfully do the OpenCV setup.
  175. imgPreview = (ImageView) findViewById(R.id.siftDisplay);
  176. btnCapturePicture = (Button) findViewById(R.id.btnImageCapture);
  177.  
  178. btnCapturePicture.setOnClickListener(new View.OnClickListener() {
  179. @Override
  180. public void onClick(View v) {
  181. captureImage();
  182. }
  183. });
  184. } break;
  185. default:
  186. {
  187. super.onManagerConnected(status);
  188. } break;
  189. }
  190. }
  191. };
  192.  
  193. public static int Matching (Mat img, String[] descPaths, float ratio) {
  194. //utworzenie deskryptora sift dla zadanego obrazka (zdjecia)
  195. SiftExtractor sift1 = new SiftExtractor(img, 3);
  196. //Pobranie deskryptora (zmienic na private, dodac funkcje get
  197. Mat qDesc = sift1.descriptors;
  198. sift1 = null; //zwalniamy obiekt
  199. //tworzymy obiekt matchera poslugujacego sie algorytmem FLANN (z OpenCV)
  200. DescriptorMatcher dm = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
  201. //Lista dopasowan
  202. List<MatOfDMatch> matchesList = new ArrayList<MatOfDMatch>();
  203. //tablica pomocnicza z poj dopasowaniem
  204. DMatch [] dArr = new DMatch[2];
  205. int descCount = descPaths.length;
  206. Mat tmpDesc;
  207. //tablica przechowujaca ilosc dobrych dopasowan obrazu wzorcowego z kazdym z deskryptorow
  208. //z niej wybierana bedzie najwieksza ilsoc dopasown - dzieki temu wiadomo do ktorego deskryptora
  209. //dopasowano obrazek - indeks tablicy to indeks deskryptora w tablicy descPaths
  210. int [] goodMatchesCount = new int[descCount];
  211. //indeks elementu z maksimalna wartoscia, na pocz ustawiamy na 0 - klasyczny alg wyszukiw max
  212. int maxIdx = 0;
  213. try {
  214. //po wszystkich deskryptorach
  215. for (int i = 0; i < descCount; ++i) {
  216. //wczytujemy z pliku - w aplikacji rzeczywistej niedopuszczalne ciagle wczytywanie z pliku - nieoptymalne
  217. //ale nie mozna tego przechowywac w pamieci bo jeden deskryptor moze miec nawet kilka MB
  218. tmpDesc = SiftExtractor.ReadDescriptorFromFile(descPaths[i]);
  219. //dopasowanie algorytmem k-NN (w tym wyp. 2 najblizszych sasiadow) - patrz dokumentacja i internet
  220. dm.knnMatch(qDesc, tmpDesc, matchesList, 2);
  221. //po wszystkich dopasowaniach
  222. for (MatOfDMatch match : matchesList) {
  223. //pobranie do tabl pomocniczej
  224. dArr = match.toArray();
  225. //spr stosunku odleglosci dopasowan - patrz praca
  226. if (dArr[0].distance/dArr[1].distance < ratio)
  227. //mniejszy niz ratio, inkrementujemy licznik
  228. goodMatchesCount[i]++;
  229. }
  230. //jesli wart biez el tablicy wieksza od max, przypisujemy indeks noweg maxa
  231. if (goodMatchesCount[i] > goodMatchesCount[maxIdx]) maxIdx = i;
  232. }
  233. //czyscimy liste do ponownego uzycia
  234. matchesList.clear();
  235. }
  236. catch(IOException e) {
  237. //exception handling
  238. e.printStackTrace();
  239. }
  240. return maxIdx; //zwracamy znaleziony max
  241. }
  242. /*
  243.  
  244.  
  245.  
  246.  
  247.  
  248.  
  249. /**
  250. * Method for starting ChickenActivity with the use of the button's click
  251. */
  252. private void setChickenView() {
  253.  
  254. //Button btn3 = (Button)findViewById(R.id.startChickenActivity);
  255. // btn3.setOnClickListener(new View.OnClickListener() {
  256.  
  257. // @Override
  258. // public void onClick(View v) {
  259. startActivity(new Intent(SiftActivity.this, ChickenActivity.class));
  260.  
  261. // }
  262. // });
  263.  
  264. }
  265. /**
  266. * Method for starting TomatoActivity with the use of the button's click
  267. */
  268. private void setTomatoView() {
  269.  
  270. //Button btn2 = (Button)findViewById(R.id.startTomatoActivity);
  271. //btn2.setOnClickListener(new View.OnClickListener() {
  272.  
  273. // @Override
  274. // public void onClick(View v) {
  275. startActivity(new Intent(SiftActivity.this, Tomato.class));
  276.  
  277. // }
  278. // });
  279. }
  280. /**
  281. * Method for starting BananaActivity with the use of the button's click
  282. */
  283. private void setBananaView() {
  284. // Button btn = (Button)findViewById(R.id.startBananaActivity);
  285. // btn.setOnClickListener(new View.OnClickListener() {
  286.  
  287. // @Override
  288. // public void onClick(View v) {
  289. // startActivity(new Intent(SiftActivity.this, BananaActivity.class));
  290.  
  291. }
  292. // });
  293. //}
  294.  
  295. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement