在RK3399Linux系统上编译一个关于边缘检测的动态链接库:
1、编写源代码,创建一个名为edge_detection.cpp。为以下代码:
#include <opencv2/opencv.hpp>
extern "C" void detectEdges (const char* input_path, const char* output_path) {
// 读取图像
cv::Mat image = cv::imread(input_path, cv::IMREAD_GRAYSCALE);
if (image.empty()) {
std::cerr << "Error: Could not read the image." << std::endl;
return;
}
// 进行边缘检测
cv::Mat edges;
cv::Canny(image, edges, 50, 150);
// 保存结果图像
cv::imwrite(output_path, edges);
}
这个代码定义了一个函数 detectEdges,该函数接受输入图像路径和输出图像路径,然后对输入图像进行边缘检测,将结果保存到输出路径。
2、编写edge_detection.h头文件:
#ifndef EDGE_DETECTION_H
#define EDGE_DETECTION_H
#ifdef __cplusplus
extern "C" {
#endif
// Function declaration for edge detection
void detectEdges (const char* input_path, const char* output_path);
#ifdef __cplusplus
}
#endif
#endif
3、编写CMakeLists.txt文件,该txt是用来生成.so ---- 动态链接库。
cmake_minimum_required(VERSION 3.0)
project(edge_detection)
# 设置 C++ 编译器
set(CMAKE_CXX_STANDARD 11)
# 添加 OpenCV 包
find_package(OpenCV REQUIRED)
# 添加源文件
add_library(edge_detection SHARED edge_detection.cpp)
# 链接 OpenCV 库
target_link_libraries(edge_detection ${OpenCV_LIBS})
4、cmake make 之后就会发现当前目录出现一个.so文件。在当前目录下创建lib文件夹,并将.so动态链接库放入lib文件夹下。
5、编译主函数:
#include <iostream>
#include "edge_detection.h"
int main() {
const char* input_path = "input.jpg";
const char* output_path = "output.jpg";
perform_edge_detection(input_path, output_path);
std::cout << "Edge detection completed. Output saved to: " << output_path << std::endl;
return 0;
}
6、编译项目工程的CMakeLIsts.txt:
cmake_minimum_required(VERSION 3.10)
project(edge_detection_app)
Find_package(OpenCV REQUIRED)
# 设置 C++ 编译器
set(CMAKE_CXX_STANDARD 11)
include_directories(${OpenCV_INCLUDE_DIR})
#添加包含路径,将 lib 目录添加到头文件搜索路径
Include_directories(${CMAKE_SOURCE_DIR}/lib)
# 添加生成的动态链接库
add_executable(edge_detection_app main_edge.cpp)
target_link_libraries(edge_detection_app ${OpenCV_LIBS}${CMAKE_SOURCE_DIR}/lib/libedge_detection.so)
7、在终端执行 cmake make ./edge_detection_app 边缘检测的结果会保存到当前目录下。