cpp
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
__global__ void sobel_gpu(unsigned char* in, unsigned char* out,
const int Height, const int Width)
{
int x = threadIdx.x + blockDim.x * blockIdx.x;
int y = threadIdx.y + blockDim.y * blockIdx.y;
int index = y * Width + x;
unsigned char x0, x1, x2, x3, x4, x5, x6, x7, x8;
int Gx = 0, Gy = 0;
if(x > 0 && x < Width - 1 && y > 0 && y < Height - 1) {
x0 = in[(y - 1) * Width + (x - 1)];
x1 = in[(y - 1) * Width + x];
x2 = in[(y - 1) * Width + x + 1];
x3 = in[y * Width + x - 1];
x4 = in[y * Width + x];
x5 = in[y * Width + x + 1];
x6 = in[(y + 1) * Width + (x - 1)];
x7 = in[(y + 1) * Width + x];
x8 = in[(y + 1) * Width + (x + 1)];
Gx = (x0 + 2 * x3 + x6) - (x2 + 2 * x5 + x8);
Gy = (x0 + 2 * x1 + x2) - (x6 + 2 * x7 + x8);
out[index] = (abs(Gx) + abs(Gy)) / 2;
}
}
int main()
{
cv::Mat img = cv::imread("noise.png", 0);
int height = img.rows;
int width = img.cols;
cv::Mat gaussImg;
GaussianBlur(img, gaussImg, cv::Size(3,3), 0,0, cv::BORDER_DEFAULT);
cv::Mat dst_gpu(height, width, CV_8UC1, cv::Scalar(0));
int memsize = height * width * sizeof(unsigned char);
unsigned char* in_gpu, *out_gpu;
cudaMalloc((void**)&in_gpu, memsize);
cudaMalloc((void**)&out_gpu, memsize);
dim3 threadsBlocks(32, 32);
dim3 blocksGrid((width + threadsBlocks.x - 1) / threadsBlocks.x, (height + threadsBlocks.y - 1) / threadsBlocks.y);
cudaMemcpy(in_gpu, gaussImg.data, memsize, cudaMemcpyHostToDevice);
sobel_gpu<<<blocksGrid, threadsBlocks>>>(in_gpu, out_gpu, height, width);
cudaMemcpy(dst_gpu.data, out_gpu, memsize, cudaMemcpyDeviceToHost);
cv::imwrite("save.png", dst_gpu);
cudaFree(in_gpu);
cudaFree(out_gpu);
printf("Finished \n");
return 0;
}
CMakeLists.txt配置
cpp
cmake_minimum_required(VERSION 3.10)
project(CSobel LANGUAGES CXX CUDA)
add_definitions(-std=c++11)
option(CUDA_USE_STATIC_CUDA_RUNTIME OFF)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CUDA_STANDARD 11)
set(CMAKE_BUILD_TYPE Debug)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -O0 -Wfatal-errors -pthread -w -g")
set(OpenCV_DIR ${PROJECT_SOURCE_DIR}/../../3rdparty/opencv3.4.15)
find_package(CUDA REQUIRED)
include_directories(
${PROJECT_SOURCE_DIR}
${OpenCV_DIR}/include
)
link_directories(
${PROJECT_SOURCE_DIR}/lib
${OpenCV_DIR}/lib
)
cuda_add_executable(bilateral main.cu)
target_link_libraries(bilateral opencv_world)