Here is a good example for using cv.filter2D by OpenCV.js.
- The type of the kernel argument should be
cv.Mat() and not np.array (it's not Python where we can use np.array as OpenCV Mat).
- The destination matrix is stored in the second argument of
cv.filter2D (it is not returned as in Python).
- It is recommended to apply the filter on Grayscale input (especially not on BGRA input, because the output alpha channel may be fully transparent).
Assume gray is the input image.
Apply cv.filter2D as follows:
const KERNEL_X = cv.matFromArray(3, 3, cv.CV_32FC1, [1,1,1, 0,0,0, -1,-1,-1]);
cv.filter2D(gray, img_prewittx, -1, KERNEL_X)
Complete code sample:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello OpenCV.js</title>
</head>
<body>
<p id="status">OpenCV.js is loading...</p>
<div>
<div class="inputoutput">
<img id="imageSrc" alt="No Image" />
<div class="caption">imageSrc <input type="file" id="fileInput" name="file" /></div>
</div>
<div class="inputoutput">
<canvas id="canvasOutput" ></canvas>
<div class="caption">canvasOutput</div>
</div>
</div>
<script async src="opencv.js" type="text/javascript"></script>
<script type="text/javascript">
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
//Read image and execute the OpenCV code sample.
imgElement.onload = function () {
let img = cv.imread(imgElement);
let gray = new cv.Mat()
let img_prewittx = new cv.Mat();
let img_prewitty = new cv.Mat();
if (img.channels() == 4)
{
cv.cvtColor(img, gray, cv.COLOR_BGRA2GRAY); //Convert from BGRA to Grayscale.
}
else if (img.channels() == 3)
{
cv.cvtColor(img, gray, cv.COLOR_BGR2GRAY); //Convert from BGR to Grayscale.
}
else
{
gray = img.clone();
}
//const prewitt = new cv.Mat()
//const KERNEL_X = np.array([[1,1,1],[0,0,0],[-1,-1,-1]])
//const KERNEL_Y = np.array([[-1,0,1],[-1,0,1],[-1,0,1]])
const KERNEL_X = cv.matFromArray(3, 3, cv.CV_32FC1, [1,1,1, 0,0,0, -1,-1,-1]);
const KERNEL_Y = cv.matFromArray(3, 3, cv.CV_32FC1, [-1,0,1, -1,0,1, -1,0,1]);
//https://answers.opencv.org/question/224848/how-do-i-create-and-use-a-custom-kernel-with-cvfilter2d/
cv.filter2D(gray, img_prewittx, -1, KERNEL_X)
cv.filter2D(gray, img_prewitty, -1, KERNEL_Y)
cv.imshow('canvasOutput', img_prewittx); //Show img_prewittx for testing
img.delete();
gray.delete();
img_prewittx.delete();
img_prewitty.delete();
};
//check openCV
var Module = {
// https://emscripten.org/docs/api_reference/module.html#Module.onRuntimeInitialized
onRuntimeInitialized() {
document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
};
</script>
</body>
</html>