在Ubuntu上安装OpenCV
OpenCV是一个多平台开源计算机视觉库。
OpenCV是Ubuntu Universe包存储库的一部分。
Ubuntu OpenCV与Python
OpenCV使用Python绑定有三种选择。
我们可以在Python 2版本或者Python 3版本或者两者之间进行选择。
要使用Python 2绑定在Ubuntu 18.04上安装OpenCV 2绑定打开终端并输入:
$ sudo apt -y install python-opencv
通过加载适当的“CV2”库来确认正确的OpenCV安装:
$ python Python 2.7.14+ (default, Nov 6 2015, 19:12:18) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> cv2._version__ '3.2.0' >>>
在使用Python 3绑定上安装opencv在Ubuntu 18.04上执行:
$ sudo apt -y install python3-opencv
通过加载适当的“CV2”库来确认正确的OpenCV安装:
$ python3 Python 3.6.4+ (default, Nov 12 2015, 08:25:03) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> cv2.__version__ '3.2.0' >>>
Opencv Python测试示例
让我们执行一个示例Opencv Python测试来消除图像示例中的噪声。将以下代码保存在主目录中的新“denoise.py”文件中:
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('gray_DSC00931.png')
b,g,r = cv2.split(img) # get b,g,r
rgb_img = cv2.merge([r,g,b]) # switch it to rgb
# Denoising
dst = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)
b,g,r = cv2.split(dst) # get b,g,r
rgb_dst = cv2.merge([r,g,b]) # switch it to rgb
plt.subplot(211),plt.imshow(rgb_img)
plt.subplot(212),plt.imshow(rgb_dst)
plt.show()
安装上面代码所需的Pythonmatplotlib。
如果使用Python 3版本,请务必使用数字3后缀Python关键字:
$ sudo apt install python3-matplotlib
使用wget命令获取示例图像:
$ wget -O ~/opencv-sample.png https://onitroad.com/images/opencv-sample.png
最后,执行上述opencv python代码:
$ python3 denoise.py
测试成功。
Ubuntu 使用C++的OpenCV
以下Linux命令将使用C++库在Ubuntu 18.04上安装OpenCV:
$ sudo apt install libopencv-dev
OpenCV库现在安装在/usr/include/opencv2目录中。
C++ Opencvs示例
将以下代码存储到主目录中的新img-display.cpp文件中:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
if( argc != 2)
{
cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
return -1;
}
Mat image;
image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file
if(! image.data ) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
waitKey(0); // Wait for a keystroke in the window
return 0;
}
编译上述代码以生成“img display”可执行二进制文件:
$ g++ img-display.cpp -o img-display `pkg-config --cflags --libs opencv`
下载图片示例:
$ wget -O ~/onitroad_logo.png https://onitroad.com/images/onitroad_logo.png
使用img-display查看图片:
$ ./img-display onitroad_logo.png
日期:2020-07-07 20:55:46 来源:oir作者:oir
