1. 官方安装包还是必不可少的,例子和文档齐备,是必须的。
可前往官网下载:Releases - OpenCV
2. 解压到目录
有C++, PYTHON, JAVA的例子,满足不同环境要求
3. 安装编译环境及依赖包
windows下要配置太麻烦了,还是ubuntu下简洁些, 主要是cmake和依赖包安装
sudo apt-get install cmake
sudo apt-get install build-essential libgtk2.0-dev libvtk7-dev libjpeg-dev libtiff5-dev libopenexr-dev libtbb-dev
4. 编译生成需要的库
如果是arm平台的,本地编译是必须的。
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..
make
实际如果遇到读写目录有权限问题的,增加sudo
其中,【cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local …】语句的含义为设置安装目录
上面的的编译命令有个问题,就是不能生成PKG-CONFIG所需的文件,所以需要用下面的选项打开
cmake -D CMAKE_BUILD_TYPE=Release -D OPENCV_GENERATE_PKGCONFIG=ON -D CMAKE_INSTALL_PREFIX=/usr/local ..
编译通过后,再运行
sudo make install
完成库文件的拷贝和路径更新
这之后
/usr/local/lib/pkgconfig目录中就会多一个opencv4.pc文件出来,之后就可以用pkgconfig的相关命令来引用opencv4的库路径了。
编译比较慢,一般要个十来分钟。
5. 配置opencv环境
需要为程序指定openvc的头文件位置,这里使用pkg-config命令来完成。
进入/etc/profile配置文件,在文件末尾追加添加以下命令:
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
source profile
pkg-config --modversion opencv
3.2.0
这个版本号,说明路径不对,还要配置到新的4.5.1版本库,才算安装成功。
(base) hy@hy-Mi-Gaming-Laptop-15-6:/usr/local$ pkg-config --modversion opencv4
4.5.1
这个地方还影响了后面使用pkg-config制定opencv路径时的版本,所以一定要设置对,原先走了些弯路。
应该查看opencv4.pc文件生成的目录,然后拷贝到pkg-config的配置目录/usr/local/lib/pkg-config,然后改名为 opencv.pc
再用 pkg-config --modversion opencv 命令检查确认是当前安装的最新版本。
还需要
/etc/bash.bashrc中LD_LIBRARY_PATH加入/usr/local/lib
sudo gedit /etc/bash.bashrc
# 在文件末尾加入
export LD_LIBRARY_PATH=/home/hy/dev/opencv-4.5.1/build/lib:$LD_LIBRARY_PATH
source /etc/bash.bashrc
在.bashrc文件里添加
export PKG_CONFIG_PATH=~/opencv/opencv-4.1.1/build/installed/lib/pkgconfig
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/opencv/opencv-4.1.1/build/installed/lib
只需修改PKG_CONFIG_PATH和LD_LIBRARY_PATH为所选的版本即可
在建立c++工程时,编写cmake文件时需要找到所需版本对应的OpenCVConfig.cmake文件,如下
cmake_minimum_required(VERSION 2.8)
set(OpenCV_DIR "~/opencv-3.4.1/build")
project(test)
find_package(OpenCV REQUIRED)
6. vs查看,sample目录下有大量的例子程序
我们可以在这里新建自己的目录,来测试学习的例子程序
就第一个example_cmake就挺好
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include
using namespace cv;
using namespace std;
void drawText(Mat & image);
int main()
{
cout << "Built with OpenCV " << CV_VERSION << endl;
Mat image;
VideoCapture capture;
capture.open(0);
if(capture.isOpened())
{
cout << "Capture is opened" << endl;
while(1)
{
capture >> image;
if(image.empty()){
cout << "Capture failure. " << endl;
break;}
drawText(image);
imshow("Sample", image);
if(waitKey(10) ==27){
break;}
}
}
else
{
cout << "No capture" << endl;
image = Mat::zeros(480, 640, CV_8UC1);
drawText(image);
imshow("Sample", image);
waitKey(0);
}
return 0;
}
void drawText(Mat & image)
{
putText(image, "Hello OpenCV",
Point(20, 50),
FONT_HERSHEY_COMPLEX, 1, // font face and scale
Scalar(255, 255, 255), // white
1, LINE_AA); // line thickness and type
}
有两种编译方式:
1. 编辑makefile运行cmake
hy@ubuntu:~/dev/opencv-4.5.1/samples/cpp/example_cmake$ cmake .
-- OpenCV library status:
-- config: /usr/share/OpenCV
-- version: 3.2.0
-- libraries: opencv_calib3d;opencv_core;opencv_features2d;opencv_flann;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_shape;opencv_stitching;opencv_superres;opencv_video;opencv_videoio;opencv_videostab;opencv_viz;opencv_aruco;opencv_bgsegm;opencv_bioinspired;opencv_ccalib;opencv_datasets;opencv_dpm;opencv_face;opencv_freetype;opencv_fuzzy;opencv_hdf;opencv_line_descriptor;opencv_optflow;opencv_phase_unwrapping;opencv_plot;opencv_reg;opencv_rgbd;opencv_saliency;opencv_stereo;opencv_structured_light;opencv_surface_matching;opencv_text;opencv_ximgproc;opencv_xobjdetect;opencv_xphoto
-- include path: /usr/include;/usr/include/opencv
-- Configuring done
-- Generating done
-- Build files have been written to: /home/hy/dev/opencv-4.5.1/samples/cpp/example_cmake
hy@ubuntu:~/dev/opencv-4.5.1/samples/cpp/example_cmake$ make
[100%] Built target opencv_example
这个makefile可以作为其他粒子的参考,通过编辑CMakeLists.txt就可以
# cmake needs this line
cmake_minimum_required(VERSION 3.1)
# Define project name
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 will
# be 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}")
# Declare the executable target built from your sources
add_executable(opencv_example example.cpp)
# Link your application with OpenCV libraries
target_link_libraries(opencv_example PRIVATE ${OpenCV_LIBS})
方法2 命令行调用GCC
g++ sourcefile -o runfile
sourcefile是cpp文件名, runfile是可执行文件名,但是会报错
hy@ubuntu:~/dev/opencv-4.5.1/samples/cpp/example_cmake$ g++ example.cpp -o run
/tmp/ccLecg3B.o: In function `main':
example.cpp:(.text+0x6c): undefined reference to `cv::VideoCapture::VideoCapture()'
example.cpp:(.text+0x80): undefined reference to `cv::VideoCapture::open(int)'
example.cpp:(.text+0x8f): undefined reference to `cv::VideoCapture::isOpened() const'
example.cpp:(.text+0xc6): undefined reference to `cv::VideoCapture::operator>>(cv::Mat&)'
example.cpp:(.text+0x176): undefined reference to `cv::imshow(cv::String const&, cv::_InputArray const&)'
example.cpp:(.text+0x19e): undefined reference to `cv::waitKey(int)'
example.cpp:(.text+0x1f7): undefined reference to `cv::Mat::zeros(int, int, int)'
example.cpp:(.text+0x276): undefined reference to `cv::imshow(cv::String const&, cv::_InputArray const&)'
example.cpp:(.text+0x29e): undefined reference to `cv::waitKey(int)'
example.cpp:(.text+0x2b5): undefined reference to `cv::VideoCapture::~VideoCapture()'
example.cpp:(.text+0x354): undefined reference to `cv::VideoCapture::~VideoCapture()'
/tmp/ccLecg3B.o: In function `drawText(cv::Mat&)':
example.cpp:(.text+0x461): undefined reference to `cv::putText(cv::_InputOutputArray const&, cv::String const&, cv::Point_
/tmp/ccLecg3B.o: In function `cv::String::String(char const*)':
example.cpp:(.text._ZN2cv6StringC2EPKc[_ZN2cv6StringC5EPKc]+0x4d): undefined reference to `cv::String::allocate(unsigned long)'
/tmp/ccLecg3B.o: In function `cv::String::~String()':
example.cpp:(.text._ZN2cv6StringD2Ev[_ZN2cv6StringD5Ev]+0x14): undefined reference to `cv::String::deallocate()'
/tmp/ccLecg3B.o: In function `cv::Mat::~Mat()':
example.cpp:(.text._ZN2cv3MatD2Ev[_ZN2cv3MatD5Ev]+0x39): undefined reference to `cv::fastFree(void*)'
/tmp/ccLecg3B.o: In function `cv::Mat::release()':
example.cpp:(.text._ZN2cv3Mat7releaseEv[_ZN2cv3Mat7releaseEv]+0x4b): undefined reference to `cv::Mat::deallocate()'
collect2: error: ld returned 1 exit status
链接不成功,看起来应该是路径的问题
田间了pkg-config配置后就没问题了。
g++ `pkg-config opencv --cflags` example.cpp -o sample `pkg-config opencv --libs` 这样可以正常生成可执行文件
这里有个小插曲,就是虚拟机调用摄像头需要配置下
第一步是打开USB设备
第二步将摄像头配置连接到虚拟机
然后上面的例程就可以顺利执行,打开摄像头了。
错误记录:
fatal error: opencv2\opencv.hpp: No such file or directory
#include
库路径问题,此外,sudo make install也是必须的
error: ‘samples’ has not been declared
std::string image_path = samples::findFile("starry_night.jpg");
这个问题是opencv版本问题,如果上面pkg-config查看版本正确,就可以解掉。
记录下各种操作下的摄像头获取延时
1. Python获取本机摄像头
代码:
import cv2
# 1.打开摄像头
capture = cv2.VideoCapture(0)
# 2.获取捕获的分辨率
width, height = capture.get(3), capture.get(4)
print(width, height)
# 以原分辨率的一倍来捕获,
# 参数1可以直接写数字,或者OpenCV符号表示
WIDTH,HEIGHT=640,480
capture.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT)
capture.set(5, 60)
font = cv2.FONT_HERSHEY_SIMPLEX
while(True):
# 获取一帧
start = cv2.getTickCount()
ret, frame = capture.read()
end = cv2.getTickCount()
# 将这帧转换为灰度图
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.putText(frame,"width:"+str(WIDTH)+"height:"+str(HEIGHT)+' cap time:'+str((end-start)/cv2.getTickFrequency()),(50,50),font,0.8,(255,255,0))
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
capture.release() # release 关闭摄像头
本机摄像头
USB摄像头
c语言
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include
using namespace cv;
using namespace std;
void drawText(Mat & image,char *msg);
int main()
{
cout << "Built with OpenCV " << CV_VERSION << endl;
Mat image;
char msg[50];
VideoCapture capture;
capture.open(0);
capture.set(3,640);
capture.set(4,480);
if(capture.isOpened())
{
cout << "Capture is opened" << endl;
for(;;)
{
int start = getTickCount();
capture >> image;
// 停止计时
int end = getTickCount();
// 单位:s
double time = (end - start) / getTickFrequency();
sprintf(msg,"640*480 cap time: %.4f",time);
if(image.empty())
break;
drawText(image,msg);
imshow("Sample", image);
if(waitKey(10) >= 0)
break;
}
}
else
{
cout << "No capture" << endl;
image = Mat::zeros(480, 640, CV_8UC1);
drawText(image,"no cap");
imshow("Sample", image);
waitKey(0);
}
return 0;
}
void drawText(Mat & image,char *msg)
{
putText(image, msg,
Point(20, 50),
FONT_HERSHEY_COMPLEX, 1, // font face and scale
Scalar(255, 255, 255), // white
1, LINE_AA); // line thickness and type
}
编译命令
g++ `pkg-config opencv --cflags` example.cpp -o sample `pkg-config opencv --libs`
本机摄像头640*480
USB摄像头640*480
本地摄像头1024*768
USB摄像头1024*768
USB摄像头1920*1080
opencv库基本数据就这样了, 另文比较v4l2和ffmpeg库捕获摄像头的延时测试。