@wip/opencv

verification
Edited: Saturday 1 February 2025

验证安装

To ensure that OpenCV is installed correctly, we can run the following example to show how to read and display image

Python

Change path/to/image to a real path of an image, then run this demo

1import cv2 as cv
2img = cv.imread("path/to/image")
3
4cv.imshow("Display window", img)
5k = cv.waitKey(0) # Wait for a keystroke in the window

C++

Change path/to/image to a real path of an image, then build this demo with OpenCV package and run it

 1#include <string>
 2#include "opencv2/core.hpp"
 3using namespace cv;
 4
 5int main()
 6{
 7    std::string image_path = "path/to/image";
 8    Mat img = imread(image_path, IMREAD_COLOR);
 9
10    imshow("Display window", img);
11    int k = waitKey(0); // Wait for a keystroke in the window
12    return 0;
13}

JavaScript

Copy this code into an html file and open it in your web browser

 1<title>Hello OpenCV.js</title>
 2
 3<h2>Hello OpenCV.js</h2>
 4<p id="status">OpenCV.js is loading...</p>
 5<div>
 6  <div class="inputoutput">
 7    <img id="imageSrc" alt="No Image" />
 8    <div class="caption">imageSrc </div>
 9  </div>
10  <div class="inputoutput">
11    <input id="fileInput" type="file" />
12    <div class="caption">canvasOutput</div>
13  </div>
14</div>
15<script>
16  let imgElement = document.getElementById('imageSrc');
17  let inputElement = document.getElementById('fileInput');
18  inputElement.addEventListener('change', (e) => {
19    imgElement.src = URL.createObjectURL(e.target.files[0]);
20  }, false);
21  imgElement.onload = function () {
22    let mat = cv.imread(imgElement);
23    cv.imshow('canvasOutput', mat);
24    mat.delete();
25  };
26  var Module = {
27    // https://emscripten.org/docs/api_reference/module.html#Module.onRuntimeInitialized
28    onRuntimeInitialized() {
29      document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
30    }
31  };
32</script>