Dectect rectangle and crop image by OpenCV.js

Hello,

I’m building a scanner app for identity card. After taking image from camera, I’m using OpenCV.js to detect identity card and crop it.

According to what i search, I know the steps to do what I want are:

  • Convert image to gray
  • Blur it
  • Draw canny
  • Find contours
  • Draw contours
  • Crop it

The source image:

Result I wish:

But I’m stucking at step find contours to draw, right now I just can make something like this:

I need that step to complete:

Below is my code:

		let src = cv.imread('img');
		let dst = new cv.Mat();
		let ksize = new cv.Size(5, 5);
		cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY);		
		cv.Canny(dst, dst, 75, 200, 3, false);
		cv.threshold(dst, dst, 80, 255, cv.THRESH_BINARY_INV);	
		cv.imshow('canvasOutput', dst);		
		src.delete();
		dst.delete();

Is there anyone know how to do this, help me please!
Thank you so much!!!

2 Likes

hi,
did you find a solution for this?

I think that what you need es Rect and roi:
This should do the trick:
let src = cv.imread(‘img’);
let dst = new cv.Mat();
// You can try more different parameters
let rect = new cv.Rect(100, 100, 200, 200);
dst = src.roi(rect);
cv.imshow(‘canvasOutput’, dst);
src.delete();
dst.delete();

Hi, maybe a stupid question, but how did you integrate OpenCV.js within your ionic app to be able to get your code working?

I might actually have found a way to implement it here:

Is this how you did it?