Run inference with an openCV imageconvert Mat to Bitmap Opencv for AndroidIs there a way to run Python on Android?Strange out of memory issue while loading an image to a Bitmap objectLazy load of images in ListViewHow to check if a service is running on Android?Correct way to convert between Bitmap and Mat in OpenCV on Android?Image Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionAndroid custom image view shapeImage classification through Tensorflow gives the exact same predictionUnable to test and deploy a deeplabv3-mobilenetv2 tensorflow-lite segmentation model for inferenceAndroid / TFlite call results in a NPE

Can I say "Gesundheit" if someone is coughing?

Does the problem of P vs NP come under the category of Operational Research?

How to derive trigonometric Cartesian equation from parametric

Security measures that could plausibly last 150+ years?

When did J.K. Rowling decide to make Ron and Hermione a couple?

"Fewer errors means better products" or "Fewer errors mean better products"?

Why is “deal 6 damage” a legit phrase?

Normally Closed Optoisolators

Is it really a problem to declare that a visitor to the UK is my "girlfriend", in terms of her successfully getting a Standard Visitor visa?

Derivative is just speed of change?

How do Canadians get a visa to go to Saudi Arabia?

The grades of the students in a class

Is this popular optical illusion made of a grey-scale image with coloured lines?

Password management for kids - what's a good way to start?

Should 2FA be enabled on service accounts?

Oath of redemption: Does Emmissary of Peace reflect damage taken from Aura of the Guardian?

Are some indefinite integrals impossible to compute or just don't exist?

How to trick a fairly simplistic kill-counter?

How is Sword Coast North governed?

What is the most 'environmentally friendly' way to learn to fly?

Python π = 1 + (1/2) + (1/3) + (1/4) - (1/5) + (1/6) + (1/7) + (1/8) + (1/9) - (1/10) ...1748 Euler

Why don't short runways use ramps for takeoff?

Being told my "network" isn't PCI Complaint. I don't even have a server! Do I have to comply?

When did J.K. Rowling decide to make Harry and Ginny a couple?



Run inference with an openCV image


convert Mat to Bitmap Opencv for AndroidIs there a way to run Python on Android?Strange out of memory issue while loading an image to a Bitmap objectLazy load of images in ListViewHow to check if a service is running on Android?Correct way to convert between Bitmap and Mat in OpenCV on Android?Image Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionAndroid custom image view shapeImage classification through Tensorflow gives the exact same predictionUnable to test and deploy a deeplabv3-mobilenetv2 tensorflow-lite segmentation model for inferenceAndroid / TFlite call results in a NPE






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have an Android Project with OpenCV4.0.1 and TFLite installed.
And I want to make an inference with a pretrained MobileNetV2 of an cv::Mat which I extracted and cropped from a CameraBridgeViewBase (Android style).
But it's kinda difficult.



I followed this example.



That does the inference about a ByteBuffer variable called "imgData" (line 71, class: org.tensorflow.lite.examples.classification.tflite.Classifier)



That imgData looks been filled on the method called "convertBitmapToByteBuffer" from the same class (line 185), adding pixel by pixel form a bitmap that looks to be cropped little before.



private int[] intValues = new int[224 * 224];
Mat _croppedFace = new Mat() // Cropped image from CvCameraViewFrame.rgba() method.

float[][] outputVal = new float[1][1]; // Output value from my MobileNetV2 // trained model (i've changed the output on training, tested on python)

// Following: https://stackoverflow.com/questions/13134682/convert-mat-to-bitmap-opencv-for-android
Bitmap bitmap = Bitmap.createBitmap(_croppedFace.cols(), _croppedFace.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(_croppedFace, bitmap);

convertBitmapToByteBuffer(bitmap); // This call should be used as the example one.
// runInference();
_tflite.run(imgData, outputVal);


But, it looks that the input_shape of my NN is not correct, but I'm following the MobileNet example because my NN it's a MobileNetV2.










share|improve this question
































    0















    I have an Android Project with OpenCV4.0.1 and TFLite installed.
    And I want to make an inference with a pretrained MobileNetV2 of an cv::Mat which I extracted and cropped from a CameraBridgeViewBase (Android style).
    But it's kinda difficult.



    I followed this example.



    That does the inference about a ByteBuffer variable called "imgData" (line 71, class: org.tensorflow.lite.examples.classification.tflite.Classifier)



    That imgData looks been filled on the method called "convertBitmapToByteBuffer" from the same class (line 185), adding pixel by pixel form a bitmap that looks to be cropped little before.



    private int[] intValues = new int[224 * 224];
    Mat _croppedFace = new Mat() // Cropped image from CvCameraViewFrame.rgba() method.

    float[][] outputVal = new float[1][1]; // Output value from my MobileNetV2 // trained model (i've changed the output on training, tested on python)

    // Following: https://stackoverflow.com/questions/13134682/convert-mat-to-bitmap-opencv-for-android
    Bitmap bitmap = Bitmap.createBitmap(_croppedFace.cols(), _croppedFace.rows(), Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(_croppedFace, bitmap);

    convertBitmapToByteBuffer(bitmap); // This call should be used as the example one.
    // runInference();
    _tflite.run(imgData, outputVal);


    But, it looks that the input_shape of my NN is not correct, but I'm following the MobileNet example because my NN it's a MobileNetV2.










    share|improve this question




























      0












      0








      0








      I have an Android Project with OpenCV4.0.1 and TFLite installed.
      And I want to make an inference with a pretrained MobileNetV2 of an cv::Mat which I extracted and cropped from a CameraBridgeViewBase (Android style).
      But it's kinda difficult.



      I followed this example.



      That does the inference about a ByteBuffer variable called "imgData" (line 71, class: org.tensorflow.lite.examples.classification.tflite.Classifier)



      That imgData looks been filled on the method called "convertBitmapToByteBuffer" from the same class (line 185), adding pixel by pixel form a bitmap that looks to be cropped little before.



      private int[] intValues = new int[224 * 224];
      Mat _croppedFace = new Mat() // Cropped image from CvCameraViewFrame.rgba() method.

      float[][] outputVal = new float[1][1]; // Output value from my MobileNetV2 // trained model (i've changed the output on training, tested on python)

      // Following: https://stackoverflow.com/questions/13134682/convert-mat-to-bitmap-opencv-for-android
      Bitmap bitmap = Bitmap.createBitmap(_croppedFace.cols(), _croppedFace.rows(), Bitmap.Config.ARGB_8888);
      Utils.matToBitmap(_croppedFace, bitmap);

      convertBitmapToByteBuffer(bitmap); // This call should be used as the example one.
      // runInference();
      _tflite.run(imgData, outputVal);


      But, it looks that the input_shape of my NN is not correct, but I'm following the MobileNet example because my NN it's a MobileNetV2.










      share|improve this question
















      I have an Android Project with OpenCV4.0.1 and TFLite installed.
      And I want to make an inference with a pretrained MobileNetV2 of an cv::Mat which I extracted and cropped from a CameraBridgeViewBase (Android style).
      But it's kinda difficult.



      I followed this example.



      That does the inference about a ByteBuffer variable called "imgData" (line 71, class: org.tensorflow.lite.examples.classification.tflite.Classifier)



      That imgData looks been filled on the method called "convertBitmapToByteBuffer" from the same class (line 185), adding pixel by pixel form a bitmap that looks to be cropped little before.



      private int[] intValues = new int[224 * 224];
      Mat _croppedFace = new Mat() // Cropped image from CvCameraViewFrame.rgba() method.

      float[][] outputVal = new float[1][1]; // Output value from my MobileNetV2 // trained model (i've changed the output on training, tested on python)

      // Following: https://stackoverflow.com/questions/13134682/convert-mat-to-bitmap-opencv-for-android
      Bitmap bitmap = Bitmap.createBitmap(_croppedFace.cols(), _croppedFace.rows(), Bitmap.Config.ARGB_8888);
      Utils.matToBitmap(_croppedFace, bitmap);

      convertBitmapToByteBuffer(bitmap); // This call should be used as the example one.
      // runInference();
      _tflite.run(imgData, outputVal);


      But, it looks that the input_shape of my NN is not correct, but I'm following the MobileNet example because my NN it's a MobileNetV2.







      android opencv tensorflow tensorflow-lite






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 23:42









      TheRealBilaal

      5432 gold badges5 silver badges17 bronze badges




      5432 gold badges5 silver badges17 bronze badges










      asked Mar 26 at 16:49









      PabloPablo

      93 bronze badges




      93 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          0














          I've solved the error, but I'm sure that it isn't the best way to do it.



          Keras MobilenetV2 input_shape is: (nBatches, 224, 224, nChannels).
          I just want to predict a single image, so, nBaches == 1, and I'm working on RGB mode, so nChannels == 3



          // Nasty nasty, but works. nBatches == 2? -- _cropped.shape() == (244, 244), 3 channels.
          float [][][][] _inputValue = new float[2][_cropped.cols()][_cropped.rows()][3];

          // Fill the _inputValue
          for(int i = 0; i < _croppedFace.cols(); ++i)
          for (int j = 0; j < _croppedFace.rows(); ++j)
          for(int z = 0; z < 3; ++z)
          _inputValue [0][i][j][z] = (float) _croppedFace.get(i, j)[z] / 255; // DL works better with 0:1 values.

          /*
          Output val, has this shape, but I don't really know why.
          I'm sure that one's of that 2's is for nClasses (I'm working with 2 classes)
          But I don't really know why it's using the other one.
          */
          float[][] outputVal = new float[2][2];
          // Tensorflow lite interpreter
          _tflite.run(_inputValue , outputVal);


          On python has the same shape:
          Python prediction:
          [[XXXXXX, YYYYY]] <- Sure for the last layer that I made, this is just a prototype NN.



          Hope some one got help, and also that someone can improve the answer because this is not very optimized.






          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55362339%2frun-inference-with-an-opencv-image%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I've solved the error, but I'm sure that it isn't the best way to do it.



            Keras MobilenetV2 input_shape is: (nBatches, 224, 224, nChannels).
            I just want to predict a single image, so, nBaches == 1, and I'm working on RGB mode, so nChannels == 3



            // Nasty nasty, but works. nBatches == 2? -- _cropped.shape() == (244, 244), 3 channels.
            float [][][][] _inputValue = new float[2][_cropped.cols()][_cropped.rows()][3];

            // Fill the _inputValue
            for(int i = 0; i < _croppedFace.cols(); ++i)
            for (int j = 0; j < _croppedFace.rows(); ++j)
            for(int z = 0; z < 3; ++z)
            _inputValue [0][i][j][z] = (float) _croppedFace.get(i, j)[z] / 255; // DL works better with 0:1 values.

            /*
            Output val, has this shape, but I don't really know why.
            I'm sure that one's of that 2's is for nClasses (I'm working with 2 classes)
            But I don't really know why it's using the other one.
            */
            float[][] outputVal = new float[2][2];
            // Tensorflow lite interpreter
            _tflite.run(_inputValue , outputVal);


            On python has the same shape:
            Python prediction:
            [[XXXXXX, YYYYY]] <- Sure for the last layer that I made, this is just a prototype NN.



            Hope some one got help, and also that someone can improve the answer because this is not very optimized.






            share|improve this answer































              0














              I've solved the error, but I'm sure that it isn't the best way to do it.



              Keras MobilenetV2 input_shape is: (nBatches, 224, 224, nChannels).
              I just want to predict a single image, so, nBaches == 1, and I'm working on RGB mode, so nChannels == 3



              // Nasty nasty, but works. nBatches == 2? -- _cropped.shape() == (244, 244), 3 channels.
              float [][][][] _inputValue = new float[2][_cropped.cols()][_cropped.rows()][3];

              // Fill the _inputValue
              for(int i = 0; i < _croppedFace.cols(); ++i)
              for (int j = 0; j < _croppedFace.rows(); ++j)
              for(int z = 0; z < 3; ++z)
              _inputValue [0][i][j][z] = (float) _croppedFace.get(i, j)[z] / 255; // DL works better with 0:1 values.

              /*
              Output val, has this shape, but I don't really know why.
              I'm sure that one's of that 2's is for nClasses (I'm working with 2 classes)
              But I don't really know why it's using the other one.
              */
              float[][] outputVal = new float[2][2];
              // Tensorflow lite interpreter
              _tflite.run(_inputValue , outputVal);


              On python has the same shape:
              Python prediction:
              [[XXXXXX, YYYYY]] <- Sure for the last layer that I made, this is just a prototype NN.



              Hope some one got help, and also that someone can improve the answer because this is not very optimized.






              share|improve this answer





























                0












                0








                0







                I've solved the error, but I'm sure that it isn't the best way to do it.



                Keras MobilenetV2 input_shape is: (nBatches, 224, 224, nChannels).
                I just want to predict a single image, so, nBaches == 1, and I'm working on RGB mode, so nChannels == 3



                // Nasty nasty, but works. nBatches == 2? -- _cropped.shape() == (244, 244), 3 channels.
                float [][][][] _inputValue = new float[2][_cropped.cols()][_cropped.rows()][3];

                // Fill the _inputValue
                for(int i = 0; i < _croppedFace.cols(); ++i)
                for (int j = 0; j < _croppedFace.rows(); ++j)
                for(int z = 0; z < 3; ++z)
                _inputValue [0][i][j][z] = (float) _croppedFace.get(i, j)[z] / 255; // DL works better with 0:1 values.

                /*
                Output val, has this shape, but I don't really know why.
                I'm sure that one's of that 2's is for nClasses (I'm working with 2 classes)
                But I don't really know why it's using the other one.
                */
                float[][] outputVal = new float[2][2];
                // Tensorflow lite interpreter
                _tflite.run(_inputValue , outputVal);


                On python has the same shape:
                Python prediction:
                [[XXXXXX, YYYYY]] <- Sure for the last layer that I made, this is just a prototype NN.



                Hope some one got help, and also that someone can improve the answer because this is not very optimized.






                share|improve this answer















                I've solved the error, but I'm sure that it isn't the best way to do it.



                Keras MobilenetV2 input_shape is: (nBatches, 224, 224, nChannels).
                I just want to predict a single image, so, nBaches == 1, and I'm working on RGB mode, so nChannels == 3



                // Nasty nasty, but works. nBatches == 2? -- _cropped.shape() == (244, 244), 3 channels.
                float [][][][] _inputValue = new float[2][_cropped.cols()][_cropped.rows()][3];

                // Fill the _inputValue
                for(int i = 0; i < _croppedFace.cols(); ++i)
                for (int j = 0; j < _croppedFace.rows(); ++j)
                for(int z = 0; z < 3; ++z)
                _inputValue [0][i][j][z] = (float) _croppedFace.get(i, j)[z] / 255; // DL works better with 0:1 values.

                /*
                Output val, has this shape, but I don't really know why.
                I'm sure that one's of that 2's is for nClasses (I'm working with 2 classes)
                But I don't really know why it's using the other one.
                */
                float[][] outputVal = new float[2][2];
                // Tensorflow lite interpreter
                _tflite.run(_inputValue , outputVal);


                On python has the same shape:
                Python prediction:
                [[XXXXXX, YYYYY]] <- Sure for the last layer that I made, this is just a prototype NN.



                Hope some one got help, and also that someone can improve the answer because this is not very optimized.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 29 at 8:58

























                answered Mar 29 at 8:49









                PabloPablo

                93 bronze badges




                93 bronze badges





















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55362339%2frun-inference-with-an-opencv-image%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript