Transforming an image to black and white (not grayscale)

is there a way to thresholding an image in Xamarin.Forms or Xamarin.Android?

I'd like to thresholding every photo taken with the camera in android (one at a time), currently i am using xlabs for the camera capture.

I have searched but I have not found anything helpful. Maybe you guys can help me. :)

Upvotes: 0

Views: 1821

Answers (1)

XTL
XTL

Reputation: 1452

So to do this,you can use OpenCV Library for Android.

  1. Download from here(for e.g.) version 3.0.0
  2. Now you need to add Android Java Binding Library into your Xamarin.Android project(also you can read this great article)
  3. When Android Java Binding Library was added to your project,you need to add .jar,that was generated from OpenCV SDK via documentation(but i've made this for you, here is link of generated .jar).
  4. In your Android Java Binding Library -> Folder(Jars) add existing file(.jar that is from step 3),also you need to add shared objects to the Jar folder(from YourPathWhereIsStoreSDK/OpenCV-android-sdk/sdk/native/libs/armeabi...etc).
    Result must be similar to this:
    result of items
  5. Now in your Xamarin.Android project you must put reference to Android Java Binding Library project.
  6. See code below,how you can use this Library :).

In your splash activity(Or MainActivity) add this:

   //beware,that we need to INIT Only once,so better to put in SplashActivity
    public  MainActivity()
            {
                if (!OpenCVLoader.InitDebug())
                {
                    System.Console.WriteLine("Failed to INIT \n OpenCV Failure");
                }
                else
                {
                    System.Console.WriteLine("OpenCV INIT Succes");
                }

            }  

Now we can convert image to b/w:

void ConvertImageToBW()
    {
        Mat MatToBW = new Mat();
        using (Bitmap SourceImg = Bitmap.CreateBitmap(BitmapFactory.DecodeFile(App._file.Path)))  //App._file.Path  - path of image that we have made by camera 
        {
            if (SourceImg != null)
            {
                Utils.BitmapToMat(SourceImg,MatToBW);
                //first we convert to grayscale
                Imgproc.CvtColor(MatToBW, MatToBW, Imgproc.ColorRgb2gray);
                //now converting to b/w
                Imgproc.Threshold(MatToBW, MatToBW, 0.5 * 255, 255, Imgproc.ThreshBinary);
                using(Bitmap newBitmap = Bitmap.CreateBitmap(MatToBW.Cols(),MatToBW.Rows(),Bitmap.Config.Argb8888))
                {
                    Utils.MatToBitmap(MatToBW, newBitmap);
                    //put result in your imageView, B/W Image
                    imageView.SetImageBitmap(newBitmap);
                }
            }

        }
    }

Now just use this method into your OnActivityResult.
Enjoy!

Upvotes: 2

Related Questions