C++版本的OpenCV 5.x编译生成opencv-python==5.x(GPU版本)接口并进行调用

实现文章连接:强力推荐】基于Nvidia-Docker-Linux(Ubuntu18.04)平台:新版OpenCV5.x(C++)联合CUDA11.1(GPU)完美配置视觉算法开发环境

1、关于有粉丝私信问我怎么调用的问题

这里再说明一下,配置方法参考上述链接,具体解决调用方法如下:

1)文中我已经说得清处了,如果你之前在环境中已安装opencv-python的其他版本,那么文中提到的/usr/lib/python3/dist-packages主要是当前正在使用的cv2.so动态库存在的地方;如果你没有安装这里则不会出现,我之前安装过,所以会有,因此选择软连接的方式可以成功导入opencv5.x的版本。

在这里插入图片描述

2)路径/usr/lib/python3.6/site-packages/cv2/python-3.6/cv2.cpython-36m-x86_64-linux-gnu.so主要是你编译opencv生成的动态库(这个路径主要是与你一开始指定python路径的有关),因此可以从这里软连接或复制到刚刚上述提到的路径下面就可以了。

cp  /usr/lib/python3.6/site-packages/cv2/python-3.6/cv2.cpython-36m-x86_64-linux-gnu.so  /usr/lib/python3/dist-packages

要么复制要么软连接,如果还是不行就使用这条命令全局搜索find / -name cv2*.so,其中cv2.cpython-36m-x86_64-linux-gnu.soo才是你生成的,用这个就行。

3)如果上述方法都试过了还是不行,解决的方法就是卸载已经安装的opencv版本,直接调用,例如,我的是这样的:

卸载:

pip uninstall opencv-contrib-python
pip uninstall opencv-python

在这里插入图片描述
在这里插入图片描述

4) 还有最后一种方法,选择一个干净的docker ubuntu>=16.04的环境,从0到一开始配,例如我在doker ubuntu20.04的python3.8环境下也成功配置了:

opencv5/OpenCV/build# cd /usr/lib/python3.8/site-packages/cv2/python-3.8/
root@OVO:/usr/lib/python3.8/site-packages/cv2/python-3.8# ls /usr/lib/python3/dist-packages
LanguageSelector                                    defer                               problem_report.py
PyGObject-3.36.0.egg-info                           defer-1.0.6.egg-info                protobuf-3.6.1.egg-info
PyJWT-1.7.1.egg-info                                distro-1.4.0.egg-info               pyRFC3339-1.1.egg-info
PyNaCl-1.3.0.egg-info                               distro.py                           pycairo-1.16.2.egg-info
SecretStorage-2.3.1.egg-info                        easy_install.py                     pycups-1.9.73.egg-info
__pycache__                                         entrypoints.egg-info                pygtkcompat
_cffi_backend.cpython-38-x86_64-linux-gnu.so        entrypoints.py                      pymacaroons
_dbus_bindings.cpython-38-x86_64-linux-gnu.so       gi                                  pymacaroons-0.13.0.egg-info
_dbus_glib_bindings.cpython-38-x86_64-linux-gnu.so  google                              pyrfc3339
_ldb_text.py                                        httplib2                            python_apt-2.0.0+ubuntu0.20.4.8.egg-info
apport                                              httplib2-0.14.0.egg-info            pytz
apport_python_hook.py                               idna                                pytz-2019.3.egg-info
apt                                                 idna-2.8.egg-info                   requests
apt_inst-stubs                                      jwt                                 requests-2.22.0.egg-info
apt_inst.cpython-38-x86_64-linux-gnu.so             keyring                             requests_unixsocket
apt_pkg-stubs                                       keyring-18.0.1.egg-info             requests_unixsocket-0.2.0.egg-info
apt_pkg.cpython-38-x86_64-linux-gnu.so              language_selector-0.1.egg-info      secretstorage
aptdaemon                                           language_support_pkgs.py            setuptools
aptsources                                          launchpadlib                        setuptools-45.2.0.egg-info
blinker                                             launchpadlib-1.10.13.egg-info       simplejson
blinker-1.4.egg-info                                lazr                                simplejson-3.16.0.egg-info
cairo                                               lazr.restfulclient-0.14.2.egg-info  six-1.14.0.egg-info
certifi                                             lazr.uri-1.0.3.egg-info             six.py
certifi-2019.11.28.egg-info                         ldb.cpython-38-x86_64-linux-gnu.so  systemd
chardet                                             lsb_release.py                      systemd_python-234.egg-info
chardet-3.0.4.egg-info                              macaroonbakery                      talloc.cpython-38-x86_64-linux-gnu.so
cryptography                                        macaroonbakery-1.3.1.egg-info       urllib3
cryptography-2.8.egg-info                           nacl                                urllib3-1.25.8.egg-info
cups.cpython-38-x86_64-linux-gnu.so                 oauthlib                            wadllib
cupshelpers                                         oauthlib-3.1.0.egg-info             wadllib-1.3.3.egg-info
cupshelpers-1.0.egg-info                            pip                                 wheel
dbus                                                pip-20.0.2.egg-info                 wheel-0.34.2.egg-info
dbus_python-1.2.16.egg-info                         pkg_resources
root@OVO:/usr/lib/python3.8/site-packages/cv2/python-3.8# cp cv2.cpython-38-x86_64-linux-gnu.so /usr/lib/python3/dist-packages
root@OVO:/usr/lib/python3.8/site-packages/cv2/python-3.8# ls /usr/lib/python3/dist-packages
LanguageSelector                                    dbus_python-1.2.16.egg-info         pkg_resources
PyGObject-3.36.0.egg-info                           defer                               problem_report.py
PyJWT-1.7.1.egg-info                                defer-1.0.6.egg-info                protobuf-3.6.1.egg-info
PyNaCl-1.3.0.egg-info                               distro-1.4.0.egg-info               pyRFC3339-1.1.egg-info
SecretStorage-2.3.1.egg-info                        distro.py                           pycairo-1.16.2.egg-info
__pycache__                                         easy_install.py                     pycups-1.9.73.egg-info
_cffi_backend.cpython-38-x86_64-linux-gnu.so        entrypoints.egg-info                pygtkcompat
_dbus_bindings.cpython-38-x86_64-linux-gnu.so       entrypoints.py                      pymacaroons
_dbus_glib_bindings.cpython-38-x86_64-linux-gnu.so  gi                                  pymacaroons-0.13.0.egg-info
_ldb_text.py                                        google                              pyrfc3339
apport                                              httplib2                            python_apt-2.0.0+ubuntu0.20.4.8.egg-info
apport_python_hook.py                               httplib2-0.14.0.egg-info            pytz
apt                                                 idna                                pytz-2019.3.egg-info
apt_inst-stubs                                      idna-2.8.egg-info                   requests
apt_inst.cpython-38-x86_64-linux-gnu.so             jwt                                 requests-2.22.0.egg-info
apt_pkg-stubs                                       keyring                             requests_unixsocket
apt_pkg.cpython-38-x86_64-linux-gnu.so              keyring-18.0.1.egg-info             requests_unixsocket-0.2.0.egg-info
aptdaemon                                           language_selector-0.1.egg-info      secretstorage
aptsources                                          language_support_pkgs.py            setuptools
blinker                                             launchpadlib                        setuptools-45.2.0.egg-info
blinker-1.4.egg-info                                launchpadlib-1.10.13.egg-info       simplejson
cairo                                               lazr                                simplejson-3.16.0.egg-info
certifi                                             lazr.restfulclient-0.14.2.egg-info  six-1.14.0.egg-info
certifi-2019.11.28.egg-info                         lazr.uri-1.0.3.egg-info             six.py
chardet                                             ldb.cpython-38-x86_64-linux-gnu.so  systemd
chardet-3.0.4.egg-info                              lsb_release.py                      systemd_python-234.egg-info
cryptography                                        macaroonbakery                      talloc.cpython-38-x86_64-linux-gnu.so
cryptography-2.8.egg-info                           macaroonbakery-1.3.1.egg-info       urllib3
cups.cpython-38-x86_64-linux-gnu.so                 nacl                                urllib3-1.25.8.egg-info
cupshelpers                                         oauthlib                            wadllib
cupshelpers-1.0.egg-info                            oauthlib-3.1.0.egg-info             wadllib-1.3.3.egg-info
cv2.cpython-38-x86_64-linux-gnu.so                  pip                                 wheel
dbus                                                pip-20.0.2.egg-info                 wheel-0.34.2.egg-info
root@OVO:/usr/lib/python3.8/site-packages/cv2/python-3.8# ls
cv2.cpython-38-x86_64-linux-gnu.so
root@OVO:/usr/lib/python3.8/site-packages/cv2/python-3.8# python
bash: python: command not found
root@OVO:/usr/lib/python3.8/site-packages/cv2/python-3.8# python3
Python 3.8.10 (default, Jun 22 2022, 20:18:18) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'5.0.0-pre'
>>> cv2.cuda
<module 'cv2.cuda'>
>>> cv2.cuda

5)如果上述没有解决你的问题那就请在评论区留言编译bug或者截图,我会在留言区解答。

2、opencv5.x(GPU)测试成功

在这里插入图片描述

下面示例测试:

opencv-python==5.x测试代码

import sys
import time
import cv2
print(cv2.__version__)

### VALUES
NUM_REPEAT = 10000

### Read source image
img_src = cv2.imread(
"../datasets/VOCdevkit/VOCmask2/JPEGImages/mask0011.jpg")  # 输入你的图片
cv2.imshow('img_src', img_src)

### Run with CPU
time_start = time.time()
for i in range (NUM_REPEAT):
    img_dst = cv2.resize(img_src, (300, 300))
time_end = time.time()
print ("CPU = {0}".format((time_end - time_start) * 1000 / NUM_REPEAT) + "[msec]")
cv2.imshow('CPU', img_dst)


### Run with GPU
img_gpu_src = cv2.cuda_GpuMat() # Allocate device memory only once, as memory allocation seems to take time...
img_gpu_dst = cv2.cuda_GpuMat()
time_start = time.time()
for i in range (NUM_REPEAT):
    img_gpu_src.upload(img_src)
    img_gpu_dst = cv2.cuda.resize(img_gpu_src, (300, 300))
    img_dst = img_gpu_dst.download()
time_end = time.time()
print ("GPU = {0}".format((time_end - time_start) * 1000 / NUM_REPEAT) + "[msec]")
cv2.imshow('GPU', img_dst)


key = cv2.waitKey(0)
cv2.destroyAllWindows()

print(cv2.cuda.getCudaEnabledDeviceCount())

输出结果:

5.0.0-pre
CPU = 0.37868216037750246[msec]
GPU = 0.28145129680633546[msec]

在这里插入图片描述

由于只是简单的操作一张图片,所以从运行速度上没有多大变化,当经过一些复杂像素计算就能体现GPU的优点了。

OpenCV(c++)==5.x测试代码

cv2cuda.cc:

#include <stdio.h>
#include <chrono>
#include <opencv2/opencv.hpp>
// #include <opencv2/gpu/gpu.hpp>
#include <opencv2/core/cuda.hpp>
#include <opencv2/cudawarping.hpp>

#define NUM_REPEAT 10000

int main()
{
    
    
    cv::Mat imgSrc = cv::imread("mask0026.jpg");
    cv::imshow("imgSrc", imgSrc);

    {
    
    
        cv::Mat imgDst;
        const auto& t0 = std::chrono::steady_clock::now();
        for (int i = 0; i < NUM_REPEAT; i++) cv::resize(imgSrc, imgDst, cv::Size(300, 300));
        const auto& t1 = std::chrono::steady_clock::now();
        std::chrono::duration<double> timeSpan = t1 - t0;
        printf("CPU = %.3lf [msec]\n", timeSpan.count() * 1000.0 / NUM_REPEAT);
        cv::imshow("CPU", imgDst);
    }

    {
    
    
        cv::cuda::GpuMat imgGpuSrc, imgGpuDst;
        cv::Mat imgDst;
        const auto& t0 = std::chrono::steady_clock::now();
        for (int i = 0; i < NUM_REPEAT; i++) {
    
    
            imgGpuSrc.upload(imgSrc);
            cv::cuda::resize(imgGpuSrc, imgGpuDst, cv::Size(300, 300));
            imgGpuDst.download(imgDst);
        }
        const auto& t1 = std::chrono::steady_clock::now();
        std::chrono::duration<double> timeSpan = t1 - t0;
        printf("GPU = %.3lf [msec]\n", timeSpan.count() * 1000.0 / NUM_REPEAT);
        cv::imshow("GPU", imgDst);
    }

    cv::waitKey(0);
    return 0;
}

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(cv2cuda cv2cuda.cc)

# Link your application with OpenCV libraries
target_link_libraries(cv2cuda PRIVATE ${OpenCV_LIBS})

编译方法:

rm -rf build
mkdir build
cd build
cmake ..
make
./cv2cuda

输出结果:

bash run.sh 
-- The C compiler identification is GNU 7.5.0
-- The CXX compiler identification is GNU 7.5.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE  
-- Found CUDA: /usr/local/cuda (found suitable exact version "11.1") 
-- Found OpenCV: /usr (found version "5.0.0") 
-- OpenCV library status:
--     config: /usr/lib/x86_64-linux-gnu/cmake/opencv5
--     version: 5.0.0
--     libraries: opencv_3d;opencv_calib;opencv_core;opencv_dnn;opencv_features2d;opencv_flann;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_stereo;opencv_stitching;opencv_video;opencv_videoio;opencv_alphamat;opencv_aruco;opencv_barcode;opencv_bgsegm;opencv_bioinspired;opencv_ccalib;opencv_cudaarithm;opencv_cudabgsegm;opencv_cudacodec;opencv_cudafeatures2d;opencv_cudafilters;opencv_cudaimgproc;opencv_cudalegacy;opencv_cudaobjdetect;opencv_cudaoptflow;opencv_cudastereo;opencv_cudawarping;opencv_cudev;opencv_datasets;opencv_dnn_objdetect;opencv_dnn_superres;opencv_dpm;opencv_face;opencv_freetype;opencv_fuzzy;opencv_hfs;opencv_img_hash;opencv_intensity_transform;opencv_line_descriptor;opencv_mcc;opencv_optflow;opencv_phase_unwrapping;opencv_plot;opencv_quality;opencv_rapid;opencv_reg;opencv_rgbd;opencv_saliency;opencv_shape;opencv_structured_light;opencv_superres;opencv_surface_matching;opencv_text;opencv_tracking;opencv_videostab;opencv_wechat_qrcode;opencv_xfeatures2d;opencv_ximgproc;opencv_xobjdetect;opencv_xphoto;opencv_xstereo
--     include path: /usr/include/opencv5
-- Configuring done
-- Generating done
-- Build files have been written to: /demo_cv/build
[ 50%] Building CXX object CMakeFiles/cv2cuda.dir/cv2cuda.cc.o
[100%] Linking CXX executable cv2cuda
[100%] Built target cv2cuda
CPU = 0.388 [msec]
GPU = 0.345 [msec]

在这里插入图片描述

3、OpenCV5.x+cuda(C++)视频测试

C++ OPENCV5.x也可以正常使用了,pkg-config opencv5 --modversion

在这里插入图片描述

案例在官方自带的例子里面,路径为:opencv5/OpenCV/samples/cpp/example_cmake/

运行方式同上,使用cmake编译:

rm -rf build
mkdir build
cd build
cmake ..
make
./opencv_example

源码:

#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include <iostream>

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;
        for(;;)
        {
    
    
            capture >> image;
            if(image.empty())
                break;
            drawText(image);
            imshow("Sample", image);
            if(waitKey(10) >= 0)
                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
}

在这里插入图片描述

编译bug解决方法

libopencv_core.so.3.2.0: undefined reference to `dpotrf_’

Adding the flag -D WITH_LAPACK=OFF 

https://linuxconfig.org/sudo-apt-add-repository-command-not-found

切记,如果你编译的过程中,python路径没有问题,最后会编译出动态库SO的提示:

[100%] Linking CXX shared module ../../lib/python3/cv2.cpython-36-x86_64-linux-gnu.so

参考

强力推荐】基于Nvidia-Docker-Linux(Ubuntu18.04)平台:新版OpenCV5.x(C++)联合CUDA11.1(GPU)完美配置视觉算法开发环境

AI模型C++部署:【配置OpenCV4++环境】与【三种在 C++ 中部署 TensorFlow 模型的方式】【准备阶段】

猜你喜欢

转载自blog.csdn.net/weixin_41194129/article/details/126650822