Q:

Extract Rectangle to new Mat and convert to Bitmap

I want to extract rectangle in image to new Mat() and fill it with this ROI. I tried but after convert Mat to Bitmap image is corrupted.
OpenCV.Core.Rect ROI = new OpenCV.Core.Rect(leftX, leftTopY, 600, 200);
Mat croppedImage = new Mat(digitsMask, ROI);
digitsMask.CopyTo(croppedImage);

Above is code for extract ROI to new Mat.
Utils.BitmapToMat(bitmap, imageMat);
cuttedImage = FilterBitmap(imageMat);
Bitmap newBitmap = Bitmap.CreateBitmap((int)cuttedImage.Size().Width, (int)cuttedImage.Size().Height, Bitmap.Config.Argb8888);
Utils.MatToBitmap(cuttedImage, newBitmap);

Here is conversion between Mat and Bitmap. Any solutions?

A:

The copyTo function reallocates the destination matrix before the data is copied to it. To make a deep copy, use clone.
Disclaimer: This is untested code.
// create ROI
OpenCV.Core.Rect ROI = new OpenCV.Core.Rect(leftX, leftTopY, 600, 200);
// deep copy ROI to new image
Mat croppedImage = (new Mat(digitsMask, ROI)).clone();
// create bitmap
Bitmap bmp = null;
// create a new 4 channel Mat because bitmap is ARGB
Mat tmp = new Mat (croppedImage.rows(), croppedImage.cols(), CvType.CV_8U, new Scalar(4));
// convert ROI image from single channel to 4 channel
Imgproc.cvtColor(croppedImage, tmp, Imgproc.COLOR_GRAY2RGBA, 4);
// Initialize bitmap
bmp = Bitmap.createBitmap(croppedImage.cols(), croppedImage.rows(), Bitmap.Config.ARGB_8888);
// convert Mat to bitmap
Utils.matToBitmap(tmp, bmp);

