首页 > 解决方案 > 如何在opencv JS中读取图像

问题描述

如何在 opencv js 中读取图像。在 opencv javascript 文档的帮助下,我无法做到这一点。有人可以在这里写一些代码来帮助我如何在“opencv js”中读取图像

标签: javascriptopencvopencv3.0

解决方案


OpenCV.js 官方网站上的第一个教程完全符合您的要求。

我将在这里发布代码并解释它是如何工作的:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello OpenCV.js</title>
</head>
<body>
<h2>Hello OpenCV.js</h2>
<p id="status">OpenCV.js is loading...</p>
<div>
  <!-- we create 1 image element, 1 canvas element and an image source -->
  <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 type="text/javascript">
   // Here starts javascript. We save the loaded image in a variable called
   // imgElement 
   let imgElement = document.getElementById('imageSrc');
   let inputElement = document.getElementById('fileInput');
   // We add a listener which starts when an image is loaded 
   inputElement.addEventListener('change', (e) => {
      imgElement.src = URL.createObjectURL(e.target.files[0]);
   }, false);
   imgElement.onload = function() {
   // Image is loaded, we can start working with OpenCV 

   // We read the loaded image from imgElement and save it in a variable
   // we could modify later with OpenCV functions 
   let mat = cv.imread(imgElement);
   // We print the saved or modified image to the canvas element with id
   // 'canvasOutput' 
   cv.imshow('canvasOutput', mat);
   // Free memory 
   mat.delete();
   };

function onOpenCvReady() {
  document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
</script>
<script async src="opencv.js" onload="onOpenCvReady();" type="text/javascript">
</script>
</body>
</html>

您可以使用 OpenCV 函数和 OpenCV 对象修改图像。最常用的是 cv.Mat()

您可以尝试通过将 cv.imshow('canvasOutput', mat) 替换为以下代码来将之前的代码修改为 GreyScale:

let dst = new cv.Mat();
cv.cvtColor(mat, dst, cv.COLOR_RGBA2GRAY);
cv.imshow('canvasOutput', dst);

如果您没有设法在您的机器上配置它,您可以使用此链接加载 Opencv.js:https ://docs.opencv.org/3.4/opencv.js 只需更改

<script async src="https://docs.opencv.org/3.4/opencv.js"
onload="onOpenCvReady();" type="text/javascript">
</script>

推荐阅读