Real-time super-pixel segmentation
gSLICr:实时超像素分割(一个用 C++ 和 CUDA 编写的实时超像素分割库)
链接:https://github.com/carlren/gSLICr
构建系统:
CMakeLists.txt文件内容
cmake_minimum_required(VERSION 3.10)
project(gSLICr)
IF(MSVC_IDE)
set(OpenCV_STATIC OFF)
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
add_definitions(-DUSING_CMAKE=1)
ELSE(MSVC_IDE)
set(CFLAGS_WARN "-Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing")
set(CMAKE_CXX_FLAGS "-fPIC -O3 -march=native ${CFLAGS_WARN} ${CMAKE_CXX_FLAGS}")
ENDIF(MSVC_IDE)
if(APPLE)
set(CUDA_HOST_COMPILER /usr/bin/clang)
endif(APPLE)
set(OpenCV_DIR "C:/Projects/_RuntimeLib/opencv-4.8.0/build/x64/vc16/lib") # 根据实际路径修改
find_package(CUDA REQUIRED)
find_package(OpenCV REQUIRED)
include_directories(${CUDA_INCLUDE_DIRS})
include_directories(${OpenCV_INCLUDE_DIRS})
add_subdirectory(ORUtils)
set(GSLICR_LIB
gSLICr_Lib/engines/gSLICr_core_engine.h
gSLICr_Lib/engines/gSLICr_seg_engine.h
gSLICr_Lib/engines/gSLICr_seg_engine_GPU.h
gSLICr_Lib/engines/gSLICr_seg_engine_shared.h
gSLICr_Lib/engines/gSLICr_core_engine.cpp
gSLICr_Lib/engines/gSLICr_seg_engine.cpp
gSLICr_Lib/engines/gSLICr_seg_engine_GPU.cu
gSLICr_Lib/objects/gSLICr_settings.h
gSLICr_Lib/objects/gSLICr_spixel_info.h
gSLICr_Lib/gSLICr_defines.h
gSLICr_Lib/gSLICr.h
)
list(APPEND "-std=c++11 -ftree-vectorize")
SOURCE_GROUP(engines FILES ${GSLICR_LIB})
cuda_add_library(gSLICr_lib
${GSLICR_LIB}
NVTimer.h
OPTIONS -gencode arch=compute_86,code=compute_86) #更改为自己显卡算力
target_link_libraries(gSLICr_lib ${CUDA_LIBRARY})
add_executable(demo demo.cpp)
target_link_libraries(demo gSLICr_lib ${OpenCV_LIBS})
cmake 指令:
mkdir build
cd build
cmake ../
make
./demo
VS环境配置
包含目录:
库目录:
附加依赖项:
项目:
直接在项目中加入头文件:
#include "gSLICr.h"
gSLICr由4个函数
namespace gSLICr
{
namespace engines
{
class core_engine
{
private:
seg_engine* slic_seg_engine;
public:
core_engine(const objects::settings& in_settings);
~core_engine();
// Function to segment in_img
void Process_Frame(UChar4Image* in_img);
// Function to get the pointer to the segmented mask image
const IntImage * Get_Seg_Res();
// Function to draw segmentation result on out_img
void Draw_Segmentation_Result(UChar4Image* out_img);
// Write the segmentation result to a PGM image
void Write_Seg_Res_To_PGM(const char* fileName);
};
}
}
函数使用方法:
// 处理图像
gSLICr_engine->Process_Frame(in_img);
// 获取分割结果
gSLICr_engine->Draw_Segmentation_Result(out_img);
// --- 获取标签图 ---
const gSLICr::IntImage* segmentation_result = gSLICr_engine->Get_Seg_Res();
// 关键修正:传入 MEMORYDEVICE_CPU 指定获取 CPU 内存的指针
const int* label_data = segmentation_result->GetData(MEMORYDEVICE_CPU);
// 检查指针有效性
if (label_data == nullptr) {
throw std::runtime_error("Failed to get label data from CPU memory");
}
// 提取尺寸
int width = segmentation_result->noDims.x; // 列数
int height = segmentation_result->noDims.y; // 行数
// 将数据复制到 OpenCV Mat
cv::Mat labels_mat(height, width, CV_32SC1); // 32 位整数类型
std::memcpy(labels_mat.data, label_data, height * width * sizeof(int));
详细见gSLICr自带demo