在ubuntu里VSCode如何调用opencv详细说明
时间: 2023-12-31 17:03:32 浏览: 33
在 Ubuntu 中,你可以按照以下步骤将 OpenCV 集成到 VSCode 中:
1. 安装 OpenCV:
- 打开终端,并确保你的系统处于更新的状态。运行以下命令:
```
sudo apt update
sudo apt upgrade
```
- 安装 OpenCV 的依赖项。运行以下命令:
```
sudo apt install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
sudo apt install libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libdc1394-22-dev libv4l-dev libxvidcore-dev libx264-dev
```
- 克隆 OpenCV 的 GitHub 仓库。运行以下命令:
```
cd ~
git clone https://github.com/opencv/opencv.git
```
- 编译并安装 OpenCV。运行以下命令:
```
cd opencv
mkdir build
cd build
cmake ..
make -j8
sudo make install
```
2. 在 VSCode 中创建 C++ 项目:
- 打开 VSCode,并安装 C++ 扩展。
- 创建一个新的文件夹作为项目文件夹,并在其中创建一个新的 C++ 文件。
- 在终端中导航到项目文件夹,并生成 `c_cpp_properties.json` 文件用于配置 C++ 编译器和包含路径。运行以下命令:
```
cd /path/to/project_folder
code .
```
- 这将在 VSCode 中打开项目文件夹。然后,按下 `Ctrl+Shift+P` 打开命令面板,并搜索并选择 "C/C++: Edit Configurations"。
- 在 "c_cpp_properties.json" 文件中添加以下内容,其中包含了 OpenCV 的路径:
```
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/local/include/opencv4" // 添加 OpenCV 的 include 路径
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu11",
"cppStandard": "gnu++14",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}
```
- 保存并关闭 `c_cpp_properties.json` 文件。
3. 编写并运行包含 OpenCV 的 C++ 代码:
- 在 VSCode 中打开你的 C++ 文件,并添加下面的示例代码:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main() {
Mat image = imread("path_to_image.jpg"); // 替换为你的图像路径
if (image.empty()) {
cout << "Could not open or find the image." << endl;
return -1;
}
namedWindow("Display window", WINDOW_NORMAL);
imshow("Display window", image);
waitKey(0);
return 0;
}
```
- 替换 `path_to_image.jpg` 为你要加载的图像的路径。
- 保存你的代码,并在终端中导航到项目文件夹。
- 使用以下命令编译并运行代码:
```
g++ -o output main.cpp `pkg-config --cflags --libs opencv4`
./output
```
- 如果一切正常,你应该能够在一个新窗口中看到加载的图像。
现在,你可以在 VSCode 中调用 OpenCV 来处理图像了。记得在编写代码时,使用相应的 OpenCV 函数和命名空间。