Displaying image and converting to grayscale - OpenCV for Android, Java API

前端 未结 4 971
陌清茗
陌清茗 2021-02-06 18:07

I\'m writing an Android app in Eclipse that uses the OpenCV4Android API. How can I display a Mat image easily, for debugging only? In C++, according to the OpenCV

相关标签:
4条回答
  • 2021-02-06 18:41

    While this doesn't deal with the display of the image, here is a quick pure-java static method to read an image by filepath and then convert it (and write it) into grayscale.

    /**
     * Get an OpenCV matrix from an image path and write the image as grayscale.
     * @param filePath The image path.
     * @return The matrix.
     */
    public static Mat loadOpenCvImage(final String filePath) {
        Mat imgMat = Highgui.imread(filePath, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
        if (imgMat == null) {
            Log.e(TAG, "error loading file: " + filePath);
        } else {
            Log.d(TAG, "Ht: " + imgMat.height() + " Width: " + imgMat.width());
            final String outPath = filePath + "_gray.jpg";
            Log.d(TAG, outPath);
            Highgui.imwrite(outPath, imgMat);
        }
        return imgMat;
    }
    
    0 讨论(0)
  • 2021-02-06 18:48

    but the Java API for Android doesn't seem to have a namedWindow function inside org.opencv.highgui.Highgui.

    Because you have to show your image on View. Take a look at samples from WEB.

    Also, I'd like to load the image as grayscale.

    Use cvCvtColor with code CV_BGR2GRAY for such type of convertion.

    0 讨论(0)
  • 2021-02-06 18:50

    This is a sample code which would display an image (must have the image in drawable folder) in imageView using OpenCV:

     ImageVIew imgView = (ImageView) findViewById(R.id.sampleImageView);
            Mat mRgba = new MAt();
            mRgba = Utils.loadResource(MainAct.this, R.drawable.your_image,Highgui.CV_LOAD_IMAGE_COLOR);
            Bitmap img = Bitmap.createBitmap(mRgba.cols(), mRgba.rows(),Bitmap.Config.ARGB_8888);
            Utils.matToBitmap(mRgba, img);
            imgView.setImageBitmap(img);
    

    and xml must have an ImageView as below :

    <ImageView
            android:id="@+id/sampleImageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"/>
    

    Hope this helps in solving your problem..

    0 讨论(0)
  • 2021-02-06 18:52

    Summary:

    Convert image to grayscale: Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2GRAY);

    Display image: see here and here.

    0 讨论(0)
提交回复
热议问题