如何在opencv中裁剪矩形?

时间:2017-07-30 19:21:47

标签: java android opencv opencv4android

我设法从我捕获的图像中绘制两个矩形。问题是,如何裁剪它们并单独保存它们以便我可以在每个中执行我的OCR?我试过搜索,但找不到我想要的东西......

到目前为止我做了什么..

  Mat imageMat = new Mat();
  Mat resizeImg = new Mat();
  Mat hierarchy = new Mat();

  //Size(width,height)
  Size imageSize = new Size(1000,800); 

  Utils.bitmapToMat(image, imageMat);
  //Resize Image

  Imgproc.resize(imageMat,resizeImg,imageSize);

  //convert the resized image to bitmap
  image = Bitmap.createBitmap(resizeImg.cols(), resizeImg.rows(), 
  Bitmap.Config.ARGB_8888);

  //convert back to Mat
  Utils.bitmapToMat(image, imageMat);

  //Create rectangles
  Imgproc.rectangle(imageMat,new Point(0,150), new Point(500,250), new Scalar(255, 0, 255),1);
   Imgproc.rectangle(imageMat,new Point(0,500), new Point(650,650), new Scalar(255, 0, 255),1);

 //What I have tried doing
 Rect rectCrop = new Rect(0,150,500,250);
 Mat image_output= imageMat.submat(rectCrop);

 Bitmap Cropimage = Bitmap.createBitmap(imageMat.cols(), imageMat.rows(), Bitmap.Config.ARGB_8888);
Utils.bitmapToMat(Cropimage, image_output);

  //TODO: save only the content in the rectangles to MAT 

//testing purpose 
 Utils.matToBitmap(imageMat,image);
 imageView.setImageBitmap(image);

1 个答案:

答案 0 :(得分:0)

这是如何获得矩形形状的图像。

Rect rect = new Rect(x1, y1, x2, y2); 
Mat cropedMat = new Mat(mat, rect);

如果你想要你可以将croped mat转换为位图

Bitmap Cropedimage = Bitmap.createBitmap(cropedMat.cols(), cropedMat.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(cropedMat, Cropedimage);