Now that OpenCV 3 is near, I decided to start using it with CUDA. Here is a simple program showing the use of GPU and CPU for thresholding an image. I also include its version for OpenCV2.

shortSampleCpu_v2.cpp:

/* OpenCV2: Thresholding using CPU */
#include <iostream>
#include "opencv2/opencv.hpp"

using namespace cv;

int main (int argc, char* argv[])
{
    try
    {
        cv::Mat src_host = cv::imread("file.png", CV_LOAD_IMAGE_GRAYSCALE);
        cv::Mat dst;

        cv::threshold(src_host, dst, 128.0, 255.0, CV_THRESH_BINARY);

        //cv::imshow("Result", result_host);
        //cv::waitKey();
    }
    catch(const cv::Exception& ex)
    {
        std::cout << "Error: " << ex.what() << std::endl;
    }
    return 0;
}

shortSampleGpu_v2.cu:

/* OpenCV2: Thresholding using GPU */
#include <iostream>
#include "opencv2/opencv.hpp"
#include "opencv2/gpu/gpu.hpp"

using namespace cv;

int main (int argc, char* argv[])
{
    try
    {
        cv::Mat src_host = cv::imread("file.png", CV_LOAD_IMAGE_GRAYSCALE);
        cv::gpu::GpuMat dst, src;
        src.upload(src_host);

        cv::gpu::threshold(src, dst, 128.0, 255.0, CV_THRESH_BINARY);

        cv::Mat result_host;
        dst.download(result_host);
        //cv::imshow("Result", result_host);
        //cv::waitKey();
    }
    catch(const cv::Exception& ex)
    {
        std::cout << "Error: " << ex.what() << std::endl;
    }
    return 0;
}

shortSampleCpu_v3.cpp

/* OpenCV3: Thresholding using CPU */
#include <iostream>
#include "opencv2/opencv.hpp"
#include "opencv2/imgcodecs.hpp"

using namespace cv;

int main (int argc, char* argv[])
{
    try
    {
        cv::Mat src_host = cv::imread("file.png", IMREAD_GRAYSCALE);
        cv::Mat dst;

        cv::threshold(src_host, dst, 128.0, 255.0, THRESH_BINARY);

        //cv::imshow("Result", result_host);
        //cv::waitKey();
    }
    catch(const cv::Exception& ex)
    {
        std::cout << "Error: " << ex.what() << std::endl;
    }
    return 0;
}

shortSampleGpu_v3.cpp

/* OpenCV3: Thresholding using GPU */
#include <iostream>
#include "opencv2/opencv.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/cuda.hpp"
#include "opencv2/cudaarithm.hpp"

using namespace cv;

int main (int argc, char* argv[])
{
    try
    {
        cv::Mat src_host = cv::imread("file.png", IMREAD_GRAYSCALE);
        cv::cuda::GpuMat dst, src;
        src.upload(src_host);

        cv::cuda::threshold(src, dst, 128.0, 255.0, THRESH_BINARY);

        cv::Mat result_host;
        dst.download(result_host);
        //cv::imshow("Result", result_host);
        //cv::waitKey();
    }
    catch(const cv::Exception& ex)
    {
        std::cout << "Error: " << ex.what() << std::endl;
    }
    return 0;
}

Originally posted on:

https://sites.google.com/site/gustavovelascoh/blog-en/opencvandcudaasimpleprogram

Advertisements