Crop rectangle subsection on camera2 and pass it to opencv for processing

1.1k Views Asked by At

I have managed to draw an overlay rectangle so that what's inside the rectangle is the only one to be processed and the app should ignore the rest of the camera region.link to Screenshot

The problem is I want to crop the above rectangle on onimagaavailable function as shown below:

@Override
    public void onImageAvailable(ImageReader reader) {
        Image img = reader.acquireLatestImage();

       //THIS IS WHERE I WANT TO CROP THE IMAGE TO ONLY SHOW WHAT WAS IN THE 
       //   ABOVE DRAWN RECTANGLE BUT I DONT KNOW HOW, I HAVE GOOGLED FOR THE 
       // PAST WEEK ON THIS


      //after processing i should pass the image to my opencv processing 
       //algorithm   
       process(img)
    }

This is my code for drawing the rectangle overlay on top of camera2

 @Override
 protected void onDraw(Canvas canvas) { // Override the onDraw() Method
    super.onDraw(canvas);

    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(Color.WHITE);
    paint.setStrokeWidth(10);
    int width = canvas.getWidth() / 2;
    int height = canvas.getHeight() / 4;
    int height1 = canvas.getHeight() / 3;
    int height_1 = canvas.getHeight() / 10;

    int fin = canvas.getWidth() + canvas.getWidth() / 3;
    int top = height / 4;

    Log.e("top", top + "");
    canvas.drawRect(canvas.getWidth() - (canvas.getWidth() - 150), 
    canvas.getHeight() - fin, canvas.getWidth() - 150, height + top, paint);

}

Kindly help/tell me which code i can use to crop the rectangle from the ImageReader image so that i can pass the cropped image to my processing algorithm

1

There are 1 best solutions below

0
On

in onImageAvailable(), you can use Bitmap.createBitmap if it's JPEG format that you converted to bitmap

Rect rectCrop = new Rect(left,top,right,bottom);
Bitmap bitmapRotated = Bitmap.createBitmap(bitmap, rectCrop.left, rectCrop.top, rectCrop.width(), rectCrop.height(), mat, true);

if you use YUV you can reduce memory and use compressToJpeg with rectangle, it's more lighter process

yuv.compressToJpeg(rect, compress, out);