Use opencv4.5.4 to access photos, videos, and cameras under ubuntu22.04

This article mainly records some details of the recent process of learning the use of opencv.

Foreword: ubuntu22.04 OpenCV4.6.0 (c++) environment configuration

For the installation process of opencv, please refer to the following blog post. It has been tested by myself and it is effective (the problem prone area is when installing the following dependencies. Generally, an error will appear. You need to change the source yourself. Otherwise, you may not be able to open the photo or the photo will be blank. question)

sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtiff5.dev libswscale-dev libjasper-dev  

Blog reference:(3 messages) ubuntu22.04 OpenCV4.6.0 (c++) environment configuration_Luffy DoD’s blog-CSDN blog

1. Check the opencv version

Run the terminal and enter the following command to check the opencv version

pkg-config --modversion opencv4

The following situation will occur. My opencv version here is 4.5.4 (different versions display different information)

 If the following command cannot be found, it may be a problem with the opencv version. You can enter the following command to check

pkg-config opencv --modversion

2. Use c++ to access the opencv library to access photos, videos, and camera photos.

Create a new folder digital in the home directory

cd digital //Enter digital

touch CMakeLists.txt //Create cmake compiled text

mkdir -p build //Create a build folder to generate the build files required by the system

mkdir -p img //Create img folder to store photos and videos

mkdir -p src //Create a src folder to store cpp files

Here I first use the following command to display the second-level directory of digital after I implemented it.

tree -L 2

CMakeLists.txt content (cmake builds opencv project)

cmake_minimum_required(VERSION 2.8) //最低版本
project( digital )                   //项目名称
find_package( OpenCV REQUIRED )     //添加opencv库到本项目
include_directories( ${OpenCV_INCLUDE_DIRS} ) //添加opencv头文件路径
add_executable( demo src/demo.cpp )         //添加可执行文件
add_executable( demo1 src/demo1.cpp )       //这里对应三个cpp
add_executable( demo2 src/demo2.cpp )        //即访问照片、视频、摄像头
target_link_libraries( demo ${OpenCV_LIBS} ) //链接opencv库到可行性文件
target_link_libraries( demo1 ${OpenCV_LIBS} )
target_link_libraries( demo2 ${OpenCV_LIBS} )

demo.cpp content (opencv access photos)

#include <opencv2/opencv.hpp>
#include <iostream>

int main(int argc, char** argv)
{
    // 读取图片
    cv::Mat image = cv::imread("/home/zyf/digital/img/yunyun.jpg");//自己的照片

    // 确认图片读取成功
    if(image.empty())
    {
        std::cerr << "Failed to open image file." << std::endl;
        return -1;
    }
    //控制照片比例
   resize(image, image, cv::Size(500, 500));
    // 显示图片
    cv::imshow("Image with Box", image);

    // 等待按键
    cv::waitKey(0);

    return 0;

demo1.cpp content (opencv access video)

#include <opencv2/opencv.hpp>
using namespace cv;

int main()
{
    // 打开视频文件
    VideoCapture cap("/home/zyf/digital/img/video.mp4");//自己的视频文件

    // 检查视频是否成功打开
    if (!cap.isOpened())
    {
        std::cout << "Error opening video stream or file" << std::endl;
        return -1;
    }

    // 循环读取视频帧
    while (true)
    {
        Mat frame;
        // 读取当前帧
        cap >> frame;

        // 检查是否成功读取帧
        if (frame.empty())
            break;

        // 显示当前帧
        imshow("Frame", frame);

        // 按下 Esc 键退出循环
        if (waitKey(25) == 27)
            break;
    }

    // 释放VideoCapture对象和所有窗口
    cap.release();
    destroyAllWindows();

    return 0;
}

demo2.cpp content (opencv access camera)

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>

using namespace std;
using namespace cv;

int main()
{
    // 打开默认摄像头
    VideoCapture cap(0);
    if (!cap.isOpened())
    {
        cout << "无法打开摄像头!" << endl;
        return -1;
    }

    namedWindow("摄像头", WINDOW_NORMAL);

    while (true)
    {
        Mat frame;
        cap >> frame;

        // 显示视频帧
        imshow("摄像头", frame);

        // 按下空格键拍照
        if (waitKey(30) == ' ')
        {
            // 生成文件名
            time_t now = time(NULL);
            tm *ltm = localtime(&now);
            string filename = to_string(ltm->tm_year + 1900) + "-" + to_string(ltm->tm_mon + 1) + "-" + to_string(ltm->tm_mday) + "-" + to_string(ltm->tm_hour) + "-" + to_string(ltm->tm_min) + "-" + to_string(ltm->tm_sec) + ".jpg";

            // 保存图片
            imwrite(filename, frame);
            cout << "已保存照片:" << filename << endl;
        }
    }

    return 0;
}

Compilation and implementation

cd build                  //进入build文件夹
cmake ..
make

cmake ..                                                                                                                                        

make                                                                                                                                                                           ”

 

At this point we can see that the executable file will be generated in the build directory

Run executable file 

./demo     //执行demo  
./demo1     //执行demo1   
./demo 2    //执行demo2   

./demo opencv access photos

 ./demo1 opencv access video

 ./demo2 opencv access camera

Take a photo with a blank space to obtain one frame of data, a .jpg file

Note: Here Linux may appear black when accessing the camera. First access the camera in window and the following situation may occur.

 Solution:

1.Install cheese

Restart the computer

Select Virtual Machine>Removable Devices>Camera>Connection on the VMware toolbar.
Execute: sudo apt-get install cheese
Run: cheese (generally you can see the image)

2. If you find that after the cheese interface pops up, the image is a black screen, but the camera connection is correct and the buttons are inoperable, you need to check several parts:

       lsusb to see if the camera is found.
  ls /dev | grep video, check whether there is video0.
  If both of the above points are met, the part that needs to be checked is virtual machine settings>usb controller>usb compatibility>(usb2.0/3.0). If 2.0 is currently selected, select 3.0. If 3.0 is currently selected, select 2.0. Then OK.
  In the VMware toolbar, select Virtual Machine>Removable Devices>Camera>Disconnect. Then go to Virtual Machine>Removable Device>Camera Name>Connect. Then reopen cheese and find that there is already an image.

Summarize:

In Linux, opencv needs to be compiled and installed by cmake before it can be used, and the dependent libraries need to be downloaded. At the same time, the path needs to be configured. The process is still a bit troublesome. What should be paid attention to is the download of dependent packages and the configuration of the path.

references:

(3 messages) Solve the black screen problem of Ubuntu cheese under the virtual machine_ubuntu20.04 cannot open cheese_cocoaqin's blog-CSDN blog

ubuntu22.04 OpenCV4.6.0 (c++) environment configuration_Luffy DoD's blog-CSDN blog

 

Guess you like

Origin blog.csdn.net/m0_70987863/article/details/131131040