Ubuntu22.04编译和使用OpenCV

ubuntu下可以直接sudo apt install libopencv-dev,不过这里面不包含一些需要专利的算法。如果需要使用一些专利算法和不稳定的算法,必须手动下载相应的源码进行编译

依赖库


sudo apt install -y build-essential ccache cmake-qt-gui cmake gphoto2 gfortran mesa-utils pkg-config protobuf-compiler tesseract-ocr tesseract-ocr-jpn yasm

sudo apt install -y libdc1394-dev libavcodec-dev libavformat-dev libatlas-base-dev libblas-dev libblas3 libhdf5-dev

sudo apt install -y libeigen3-dev libfaac-dev libgflags-dev libgtkglext1 libgoogle-glog-dev libgoogle-glog-doc libgphoto2-dev libgtk-3-dev

sudo apt install -y libilmbase-dev libilmbase25 libjpeg-dev liblapack-dev libleptonica-dev liblapacke-dev libmp3lame-dev

sudo apt install -y libopencore-amrnb-dev libopenexr-dev libopenexr25 libprotobuf-dev libprotoc-dev libswscale-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev

sudo apt install -y libtiff5-dev libtheora-dev libtesseract-dev libv4l-dev libvorbis-dev libx264-dev libxvidcore-dev libxine2-dev

下载源码

git clone git@github.com:opencv/opencv.git
git clone git@github.com:opencv/opencv_contrib.git
mkdir buildopencv
cmake-gui

CMAKE配置

手动指定以下选项

选项 推荐取值
GLOG_INCLUDE_DIR /usr/include/glog
OPENCV_EXTRA_MODULES_PATH 你的路径/opencv_contrib/modules
BUILD_opencv_face 打×
WITH_CUDA 打×
WITH_CUDA 打×
WITH_CUFFT 打×
WITH_CUBLAS 打×
WITH_CUDNN 打×
WITH_OPENGL
OPENCV_ENABLE_NONFREE
OPENCV_GENERATE_PKGCONFIG
BUILD_opencv_world

另外,cmake过程中可能会提示一些东西下载失败,比如ipp,比如wechar qrcode,这时候你需要科学上网,或者禁用掉相关模块.face模块也在这之中

另外如果你安装了cuda驱动,则可以把上面几个叉叉打开了

如果你忘了给OPENCV_ENABLE_NONFREE打勾,那你就偷着乐吧,支持正版

编译安装

cd buildopencv
make -j20
sudo make install

vi ~/.bashrc #写入如下信息
PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
export PKG_CONFIG_PATH

sudo updatedb
sudo ldconfig

使用opencv

霍夫变换直线检测例子~~

cmakelists.txt

cmake_minimum_required(VERSION 3.5)
project(Hofuline LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# find required opencv
find_package(OpenCV REQUIRED)
# directory of opencv headers
include_directories(${OpenCV_INCLUDE_DIRS})
# directory of opencv library
link_directories(${OpenCV_LIBRARY_DIRS})

add_executable(${PROJECT_NAME} main.cpp )
# opencv libraries
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})

main.cpp

#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

using namespace cv;

int main()
{
Mat src, dst, color_dst;

src=imread("../image.bmp", 0);

Canny( src, dst, 50, 200, 3 );
cvtColor( dst, color_dst, COLOR_GRAY2BGR );

vector<Vec4i> lines;
HoughLinesP( dst, lines, 1, CV_PI/180, 80, 30, 10 );
for( size_t i = 0; i < lines.size(); i++ )
{
line( color_dst, Point(lines[i][0], lines[i][1]),
Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8 );
}

imwrite("line.bmp",color_dst);

return 0;
}