因为之前接触过 C++ 语言的 opencv,所以原理就不介绍了,只记录一下 js 语言的写法。
官网相关内容介绍:【https://docs.opencv.org/3.3.1/df/d24/tutorial_js_image_display.html】
代码示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>toGray</title>
<!--两张图片格式为左浮动,处在一行-->
<style type="text/css">
.InputOutput{
float: left;
margin: 10px;
}
</style>
</head>
<body>
<!--若 opencv.js 文件加载成功,则会显示“opencv.js is ready.”-->
<p id="status">opencv.js is loading...</p>
<!--图片读入区域-->
<div class="InputOutput">
<div class="caption">srcImg<input type="file" id="inputFile" name="file"/></div>
<img id="srcImg" alt="No Image"/>
</div>
<!--结果展示区域-->
<div class="InputOutput">
<div class="caption">dstImg</div>
<canvas id="dstImg"></canvas>
</div>
<!--将图片转换为灰度图,并在 canvas 中显示-->
<script type="text/javascript">
<!--读入图片-->
let imgElement=document.getElementById("srcImg");
let fileElement=document.getElementById("inputFile");
fileElement.addEventListener("change",
(e) => {imgElement.src = URL.createObjectURL(e.target.files[0]);},
false);
<!--转换为灰度图-->
imgElement.onload=function(){
let src=cv.imread(imgElement);
let gray = new cv.Mat();
cv.cvtColor(src, gray, cv.COLOR_RGBA2GRAY);
cv.imshow('dstImg', gray);
src.delete();
dst.delete();
};
<!--成功加载 opencv.js 后,status 标签会显示“opencv.js is ready.”-->
function onOpenCvReady(){
document.getElementById("status").innerHTML="opencv.js is ready.";
}
</script>
<script async src="opencvjs/opencv.js" onload="onOpenCvReady();" type="text/javascript"></script>
</body>
</html>
效果展示: