将 Rectangle 提取到新的 Mat 并转换为 Bitmap

Extract Rectangle to new Mat and convert to Bitmap

我想将图像中的矩形提取到新的 Mat() 中并用这个 ROI 填充它。我试过了,但在将 Mat 转换为 Bitmap 图像后,图像已损坏。

OpenCV.Core.Rect ROI = new OpenCV.Core.Rect(leftX, leftTopY, 600, 200);
Mat croppedImage = new Mat(digitsMask, ROI);
digitsMask.CopyTo(croppedImage);

以上是将 ROI 提取到新 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);

这里是Mat和Bitmap的转换。有什么解决办法吗?

copyTo function reallocates the destination matrix before the data is copied to it. To make a deep copy, use clone.

免责声明:这是未经测试的代码。

// 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);