前言
因为个人学业和兴趣原因需要用到人工智能和自动化相关的内容,计划学习一些列相关的内容。这里先以简单常见的OpenCV作为入门内容,主要是作为使用来说这个应该比较简单并且这个也比较实用。这篇文章将记录OpenCV的相关链接与入门内容。
官方主页:https://opencv.org/
项目地址:https://github.com/opencv/opencv
文档(4.11.0):https://docs.opencv.org/4.11.0/index.html
OpenCV的官网看着像是卖课的,唯一有用的信息就是文档。
项目中的samples目录下是官方的文档。
基础说明
OpenCV (Open Source Computer Vision Library) is an open-source library that includes several hundreds (2500+) of computer vision algorithms.
OpenCV早期的版本(1.x API)是基于C开发的,目前的版本是基于(2.x API)是基于C++开发的。当前的库版本是4.11.0,但API接口是2.x形式的,在C++中接口目录就是opencv2,在Python中目前用的库就是cv2。
OpenCV提供了图像处理、视频处理、特征检测等功能模块,同时为了其功能展开提供了一些数据类型(比如使用Mat来表示图像)、界面等工具类库。OpenCV的模块除了前面项目地址上的主模块(Main modules),另外还有一些附加模块(Extra modules),这部分在 opencv_contrib 仓库中。
OpenCV最基础的功能就是图像处理,可以简单理解为以编程方式使用的Photoshop。在此之上又有很多扩展的应用,比如常见的物体识别等,或者是视频方面的处理等。
OpenCV从使用的方式来说目前主要可以通过C++、Python、JavaScript、Java等语言进行使用,另外还有可供Android和IOS使用的版本。这篇文章接下来部分会分别使用前面三种语言演示OpenCV基础使用。
入门使用
OpenCV(C++)
使用C++来使用OpenCV主要有两种方式:1、从源码构建;2、使用预编译的库。从源码构建可以参考官方文档,使用预编译的库的话官方的预编译版本可以从项目仓库或者SourceForge找到。此外还有第三方的预编译的版本,比如常见的Linux发行版就有自己的预编译的版本:https://pkgs.org/search/?q=opencv
在Debian或Ubuntu中可以使用下面命令进行安装(使用这个方式安装可能版本不是最新的):
sudo apt install libopencv-dev
安装完成就可以写代码进行测试了,这里使用官方示例,通过opencv打开一张图片,代码如下:
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv ) {
if ( argc != 2 ) {
printf("usage: DisplayImage.out <Image_Path>\n");
return -1;
}
Mat image;
image = imread( argv[1], IMREAD_COLOR );
if ( !image.data ) {
printf("No image data \n");
return -1;
}
namedWindow("Display Image", WINDOW_AUTOSIZE );
imshow("Display Image", image);
waitKey(0);
return 0;
}
CMakeLists.txt如下:
cmake_minimum_required(VERSION 3.5)
project(opencv_example_project)
# Find OpenCV, you may need to set OpenCV_DIR variable to the absolute path to
# the directory containing OpenCVConfig.cmake file via the command line or GUI
find_package(OpenCV REQUIRED)
# If the package has been found, several variables willbe set,
# you can find the full list with descriptions in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS " config: ${OpenCV_DIR}")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBS}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
add_executable(opencv_example main.cpp)
target_link_libraries(opencv_example PRIVATE ${OpenCV_LIBS})
编译与演示:
编译或使用有问题通常是缺少库或者权限等问题,尝试安装下面内容:
sudo apt update && sudo apt install -y build-essential cmake g++ wget unzip
需要注意的是上面示例是来打开图片,这个必须要在带桌面的环境下才能打开。
OpenCV-Python
Python是一门用起来非常方便的语言,OpenCV也封装了可供Python调用的方式,其中有用到Numpy来进行数据操作。(OpenCV-Python中图形经常用Numpy的三维数组来表示,以提高操作速度。)
Python的基础安装与使用可以参考下面文章:
https://blog.csdn.net/Naisu_kun/article/details/129986780
安装设置Python后接着安装相关的库:
pip install numpy
pip install matplotlib # 可选的
接着安装opencv的库,有两种方式,一种是和前面C++一样从预编译的版本进行安装(在 opencv/build/python
目录下),另一种就是通过pip进行安装:
pip install opencv-python # Main modules
pip install opencv-contrib-python # Extra modules
安装完成后可以查看安装的版本:
可以使用下面代码进行测试,使用opencv读取并打开一张图片:
import cv2 as cv
import sys
img = cv.imread(cv.samples.findFile("logo-nx.png")) # read image
if img is None:
sys.exit("Could not read the image.")
cv.imshow("Display window", img)
k = cv.waitKey(0) # wait press one key to exit
测试结果如下:
OpenCV.js(4.11.0+)
随着硬件性能的快速提高,随着H5/CSS3/ES6等标准的发布,随着WebAssembly技术的出现,JavaScript是越来越吃香的。OpenCV.js的出现也是受到前面这些诸多因素的影响,毕竟浏览器现在才是最大的平台,目前的移动端和桌面端的很多应用程序都是基于浏览器内核的网页,常见的相似VSCode就是这类。
通过JS使用OpenCV首先需要获取 opencv.js
文件,获取地址比较特殊,目前是随着文档一起发布的,可以从GitHub中下载Release中的doc或者直接在官网下载文档。下载解压后 opencv.js
文件在根目录中:
需要注意的是目前 4.11.0
版本编译生成的 opencv.js
和之前版本有所不同,现在这个对象变成了 Promise
类型,需要使用异步方式去调用,但目前官方文档中还未改,会导致参考官方文档的例程报 Uncaught TypeError: cv.imread is not a function
等异常。具体情况可以参考:https://github.com/opencv/opencv/issues/27129
所以在使用 4.11.0+
版本的 opencv.js
时,文档请参考更高版本的,比如 4.12.0-dev 。
下面是个最基本的示例,使用opencv打开一张图片,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello OpenCV.js</title>
</head>
<body>
<div>
<h2>Hello OpenCV.js</h2>
<p id="status">OpenCV.js is loading...</p>
<div><input type="file" id="imgInput"/></div>
<canvas id="canvasOutput"></canvas>
</div>
<script type="text/javascript">
let status = document.querySelector("#status");
let imgInput = document.querySelector("#imgInput");
let imgElement = document.createElement("img");
// 当选择输入图片后将图片加载到创建的img节点上
imgInput.onchange = (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}
// 当img节点加载图片时读取图片并显示到canvas节点
imgElement.onload = async function () {
cv = (cv instanceof Promise) ? await cv : cv;
let mat = cv.imread(imgElement); // read an image from html canvas or img element
cv.imshow('canvasOutput', mat);
mat.delete();
};
</script>
<script>
const Module = {}; // https://emscripten.org/docs/api_reference/module.html#Module.onRuntimeInitialized
Module.onRuntimeInitialized = () => { status.innerText = 'OpenCV.js is ready.'; };
</script>
<script async src="opencv.js" type="text/javascript"></script>
</body>
</html>
保存文件为html格式,并通过浏览器打开即可使用:
后记
OpenCV非常流行,很多图像/视频中目标检测相关功能都是用它来实现的,很多本科生的毕生都用它来做。整体来说目前之间要用起来还是比较简单的。本文目前只是使用三种语言简单的安装并使用了下,还未涉及到OpenCV具体的功能,之后会进一步展开。