Advertisement
Guest User

MainActivity.java

a guest
Feb 12th, 2020
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.34 KB | None | 0 0
  1. package com.example.opencvv2;
  2.  
  3. import android.os.Bundle;
  4. import android.os.Environment;
  5. import android.util.Log;
  6. import android.view.SurfaceView;
  7. import android.view.View;
  8.  
  9. import androidx.appcompat.app.AppCompatActivity;
  10.  
  11. import org.opencv.android.BaseLoaderCallback;
  12. import org.opencv.android.CameraBridgeViewBase;
  13. import org.opencv.android.JavaCameraView;
  14. import org.opencv.android.OpenCVLoader;
  15. import org.opencv.core.Core;
  16. import org.opencv.core.CvType;
  17. import org.opencv.core.Mat;
  18. import org.opencv.core.MatOfFloat;
  19. import org.opencv.core.MatOfInt;
  20. import org.opencv.core.MatOfRect;
  21. import org.opencv.core.Point;
  22. import org.opencv.core.Rect;
  23. import org.opencv.core.Scalar;
  24. import org.opencv.core.Size;
  25. import org.opencv.dnn.Dnn;
  26. import org.opencv.dnn.Net;
  27. import org.opencv.imgproc.Imgproc;
  28. import org.opencv.utils.Converters;
  29.  
  30. import java.io.File;
  31. import java.util.ArrayList;
  32. import java.util.Arrays;
  33. import java.util.List;
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40. public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
  41.  
  42.     private static String TAG = "MainActivity";
  43.     CameraBridgeViewBase cameraBridgeViewBase;
  44.     BaseLoaderCallback baseLoaderCallback;
  45.     boolean startYolo = false;
  46.     boolean firstTimeYolo = false;
  47.     Net tinyYolo;
  48.     //String config =  getExternalFilesDir("")+ "/deepNeuralNets/yolov3-tiny.cfg";
  49.     //String weights =  getExternalFilesDir("")+ "/deepNeuralNets/yolov3-tiny.weights";
  50.  
  51.     public void YOLO(View Button){
  52.  
  53.         if (startYolo == false){
  54.  
  55.  
  56.  
  57.  
  58.             startYolo = true;
  59.  
  60.             if (firstTimeYolo == false){
  61.  
  62.                 firstTimeYolo = true;
  63.                 //String tinyYoloCfg = Environment.getExternalStorageDirectory() + "/deepNeuralNets/yolov3-tiny.cfg" ;
  64.                 //String tinyYoloWeights = Environment.getExternalStorageDirectory() + "/deepNeuralNets/yolov3-tiny.weights";
  65.  
  66.                 tinyYolo = Dnn.readNetFromDarknet("/storage/emulated/0/deepNeuralNets/yolov3-tiny.cfg", "/storage/emulated/0/deepNeuralNets/yolov3-tiny.weights");
  67.                 //tinyYolo = Dnn.readNet(weights);
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.             }
  77.  
  78.  
  79.  
  80.         }
  81.  
  82.         else{
  83.  
  84.             startYolo = false;
  85.  
  86.  
  87.         }
  88.  
  89.  
  90.  
  91.  
  92.     }
  93.  
  94.  
  95.  
  96.  
  97.  
  98.  
  99.     @Override
  100.     protected void onCreate(Bundle savedInstanceState) {
  101.         super.onCreate(savedInstanceState);
  102.         setContentView(R.layout.activity_main);
  103.  
  104.  
  105.         cameraBridgeViewBase = (JavaCameraView)findViewById(R.id.my_camera_view);
  106.         cameraBridgeViewBase.setVisibility(SurfaceView.VISIBLE);
  107.         cameraBridgeViewBase.setCvCameraViewListener(this);
  108.  
  109.  
  110.         //System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  111.         baseLoaderCallback = new BaseLoaderCallback(this) {
  112.             @Override
  113.             public void onManagerConnected(int status) {
  114.                 super.onManagerConnected(status);
  115.  
  116.                 switch(status){
  117.  
  118.                     case BaseLoaderCallback.SUCCESS:
  119.                         cameraBridgeViewBase.enableView();
  120.                         break;
  121.                     default:
  122.                         super.onManagerConnected(status);
  123.                         break;
  124.                 }
  125.  
  126.  
  127.             }
  128.  
  129.         };
  130.  
  131.  
  132.  
  133.  
  134.     }
  135.  
  136.     @Override
  137.     public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
  138.  
  139.         Mat frame = inputFrame.rgba();
  140.  
  141.         if (startYolo == true) {
  142.  
  143.             Imgproc.cvtColor(frame, frame, Imgproc.COLOR_RGBA2RGB);
  144.  
  145.  
  146.  
  147.             Mat imageBlob = Dnn.blobFromImage(frame, 0.00392, new Size(416,416),new Scalar(0, 0, 0),/*swapRB*/false, /*crop*/true);
  148.  
  149.  
  150.             tinyYolo.setInput(imageBlob);
  151.  
  152.             //int cols = frame.cols();
  153.             //int rows = frame.rows();
  154.             //double THRESHOLD = 0.5;
  155.  
  156.             java.util.List<Mat> result = new java.util.ArrayList<Mat>(2);
  157.  
  158.             List<String> outBlobNames = new java.util.ArrayList<>();
  159.             outBlobNames.add(0, "yolo_16");
  160.             outBlobNames.add(1, "yolo_23");
  161.  
  162.             //tinyYolo.forward(/*result,outBlobNames*/"detection_out");
  163.             tinyYolo.forward(result,outBlobNames);
  164.  
  165.             float confThreshold = 0.3f;
  166.  
  167.  
  168.  
  169.             List<Integer> clsIds = new ArrayList<>();
  170.             List<Float> confs = new ArrayList<>();
  171.             List<Rect> rects = new ArrayList<>();
  172.  
  173.  
  174.  
  175.  
  176.             for (int i = 0; i < result.size(); ++i)
  177.             {
  178.  
  179.                 Mat level = result.get(i);
  180.  
  181.                 for (int j = 0; j < level.rows(); ++j)
  182.                 {
  183.                     Mat row = level.row(j);
  184.                     Mat scores = row.colRange(5, level.cols());
  185.  
  186.                     Core.MinMaxLocResult mm = Core.minMaxLoc(scores);
  187.  
  188.  
  189.  
  190.  
  191.                     float confidence = (float)mm.maxVal;
  192.  
  193.  
  194.                     Point classIdPoint = mm.maxLoc;
  195.  
  196.  
  197.  
  198.                     if (confidence > confThreshold)
  199.                     {
  200.                         int centerX = (int)(row.get(0,0)[0] * frame.cols());
  201.                         int centerY = (int)(row.get(0,1)[0] * frame.rows());
  202.                         int width   = (int)(row.get(0,2)[0] * frame.cols());
  203.                         int height  = (int)(row.get(0,3)[0] * frame.rows());
  204.  
  205.  
  206.                         int left    = centerX - width  / 2;
  207.                         int top     = centerY - height / 2;
  208.  
  209.                         clsIds.add((int)classIdPoint.x);
  210.                         confs.add((float)confidence);
  211.  
  212.  
  213.  
  214.  
  215.                         rects.add(new Rect(left, top, width, height));
  216.                     }
  217.                 }
  218.             }
  219.             int ArrayLength = confs.size();
  220.  
  221.             if (ArrayLength>=1) {
  222.                 // Apply non-maximum suppression procedure.
  223.                 float nmsThresh = 0.2f;
  224.  
  225.  
  226.  
  227.  
  228.                 MatOfFloat confidences = new MatOfFloat(Converters.vector_float_to_Mat(confs));
  229.  
  230.  
  231.                 Rect[] boxesArray = rects.toArray(new Rect[0]);
  232.  
  233.                 MatOfRect boxes = new MatOfRect(boxesArray);
  234.  
  235.                 MatOfInt indices = new MatOfInt();
  236.  
  237.  
  238.  
  239.                 Dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThresh, indices);
  240.  
  241.  
  242.                 // Draw result boxes:
  243.                 int[] ind = indices.toArray();
  244.                 for (int i = 0; i < ind.length; ++i) {
  245.  
  246.                     int idx = ind[i];
  247.                     Rect box = boxesArray[idx];
  248.  
  249.                     int idGuy = clsIds.get(idx);
  250.  
  251.                     float conf = confs.get(idx);
  252.  
  253.  
  254.                     List<String> cocoNames = Arrays.asList("a person", "a bicycle", "a motorbike", "an airplane", "a bus", "a train", "a truck", "a boat", "a traffic light", "a fire hydrant", "a stop sign", "a parking meter", "a car", "a bench", "a bird", "a cat", "a dog", "a horse", "a sheep", "a cow", "an elephant", "a bear", "a zebra", "a giraffe", "a backpack", "an umbrella", "a handbag", "a tie", "a suitcase", "a frisbee", "skis", "a snowboard", "a sports ball", "a kite", "a baseball bat", "a baseball glove", "a skateboard", "a surfboard", "a tennis racket", "a bottle", "a wine glass", "a cup", "a fork", "a knife", "a spoon", "a bowl", "a banana", "an apple", "a sandwich", "an orange", "broccoli", "a carrot", "a hot dog", "a pizza", "a doughnut", "a cake", "a chair", "a sofa", "a potted plant", "a bed", "a dining table", "a toilet", "a TV monitor", "a laptop", "a computer mouse", "a remote control", "a keyboard", "a cell phone", "a microwave", "an oven", "a toaster", "a sink", "a refrigerator", "a book", "a clock", "a vase", "a pair of scissors", "a teddy bear", "a hair drier", "a toothbrush");
  255.  
  256.  
  257.  
  258.                     int intConf = (int) (conf * 100);
  259.  
  260.  
  261.  
  262.                     Imgproc.putText(frame,cocoNames.get(idGuy) + " " + intConf + "%",box.tl(),Core.FONT_HERSHEY_SIMPLEX, 2, new Scalar(255,255,0),2);
  263.  
  264.  
  265.  
  266.                     Imgproc.rectangle(frame, box.tl(), box.br(), new Scalar(255, 0, 0), 2);
  267.  
  268.  
  269.  
  270.  
  271.  
  272.                 }
  273.             }
  274.  
  275.  
  276.  
  277.  
  278.  
  279.  
  280.  
  281.  
  282.  
  283.         }
  284.  
  285.  
  286.  
  287.         return frame;
  288.     }
  289.  
  290.  
  291.     @Override
  292.     public void onCameraViewStarted(int width, int height) {
  293.  
  294.  
  295.         if (startYolo == true){
  296.  
  297.             String tinyYoloCfg = Environment.getExternalStorageDirectory() + "/dnns/yolov3-tiny.cfg" ;
  298.             String tinyYoloWeights = Environment.getExternalStorageDirectory() + "/dnns/yolov3-tiny.weights";
  299.  
  300.             tinyYolo = Dnn.readNetFromDarknet(tinyYoloCfg, tinyYoloWeights);
  301.  
  302.  
  303.         }
  304.  
  305.  
  306.  
  307.     }
  308.  
  309.  
  310.     @Override
  311.     public void onCameraViewStopped() {
  312.  
  313.     }
  314.  
  315.  
  316.     @Override
  317.     protected void onResume() {
  318.         super.onResume();
  319.  
  320.         if (OpenCVLoader.initDebug()){
  321.             Log.d(TAG, "----------OpenCV is configured or connected successfully----------");
  322.             baseLoaderCallback.onManagerConnected(BaseLoaderCallback.SUCCESS);
  323.         }
  324.         else{
  325.             Log.d(TAG, "----------OpenCV not working or loades----------");
  326.             OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, this, baseLoaderCallback);
  327.         }
  328.  
  329.  
  330.  
  331.     }
  332.  
  333.     @Override
  334.     protected void onPause() {
  335.         super.onPause();
  336.         if(cameraBridgeViewBase!=null){
  337.  
  338.             cameraBridgeViewBase.disableView();
  339.         }
  340.  
  341.     }
  342.  
  343.  
  344.     @Override
  345.     protected void onDestroy() {
  346.         super.onDestroy();
  347.         if (cameraBridgeViewBase!=null){
  348.             cameraBridgeViewBase.disableView();
  349.         }
  350.     }
  351. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement