Skip to content

Instantly share code, notes, and snippets.

@aferust
Created February 5, 2021 09:36
Show Gist options
  • Save aferust/1d24c3722c56bfc66b1daa41d595fd98 to your computer and use it in GitHub Desktop.
Save aferust/1d24c3722c56bfc66b1daa41d595fd98 to your computer and use it in GitHub Desktop.
// https://forums.developer.nvidia.com/t/eliminate-upload-download-for-opencv-cuda-gpumat-using-shared-memory/83090/3
// SimpleTest.cpp
// Loads an image, calls a GPU enabled function that uses opencv GPUMat upload/download
//
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <stdio.h>
// cuda stuff
#include <opencv2/cudaarithm.hpp>
// Nvidia cuda api
#include <cuda_runtime.h>
using namespace std;
cv::Mat testfunction(cv::Mat& h_original) {
// receives a CPU/host based image, converts it to GPU/device based image
// manipulates it, then converts back to CPU/host based result.
cv::Mat h_result (h_original.size(), h_original.type());
// create GPU/device images, same size and type as original host image
cv::cuda::GpuMat d_original(h_original.size(), h_original.type());
cv::cuda::GpuMat d_result(h_original.size(), h_original.type());
// upload the original image from host to device
d_original.upload(h_original);
// perform a GPU operation of some sort. Using threshold for simple placeholder
cv::cuda::threshold(d_original, d_result, 128.0, 255.0, cv::THRESH_BINARY);
// download the result image from device to host
d_result.download(h_result);
return h_result;
}
int main(int argc, char *argv[]) {
cv::namedWindow("original image", cv::WINDOW_AUTOSIZE);
cv::namedWindow("modified image", cv::WINDOW_AUTOSIZE );
cv::String filename = "./lena.jpg";
cv::Mat image, newimage;
image = cv::imread(filename);
if (image.empty()) {
cout << "could not open or find the image" << endl;
return -1;]
}
newimage = testfunction(image);
cv::imshow("original image", image);
cv::imshow("modified image", newimage);
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment