# Demosaicing a bayer image with OpenCV and CUDA

**URL:** <https://forum.opencv.org/t/demosaicing-a-bayer-image-with-opencv-and-cuda/1329>\
**Category:** C++\
**Tags:** cuda, core\
**Created:** [February 4, 2021, 4:45am UTC](https://forum.opencv.org/t/demosaicing-a-bayer-image-with-opencv-and-cuda/1329 "2021-02-04T04:45:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jamesyoung](https://avatars.discourse-cdn.com/v4/letter/j/e495f1/32.png) [@jamesyoung](https://forum.opencv.org/u/jamesyoung)\
**Post date:** [February 4, 2021, 4:45am UTC](https://forum.opencv.org/t/demosaicing-a-bayer-image-with-opencv-and-cuda/1329/1 "2021-02-04T04:45:23Z")

</div>

I am trying to use cv::cuda::demosaicing and for some reason I can’t get it to work; it did work on Ubuntu 18.04 and Ubuntu 20.04 but on Windows I am not getting any output.

Here is the code:

```
#include <opencv2/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/highgui.hpp>

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char* argv[])
{
ifstream ifs("img0000.img", ios_base::binary);
streamsize size = ifs.tellg();

cout << "Reading image into buffer..." << endl;

char* buffer = new char[size];

ifs.seekg(0, ios::beg);
ifs.read(buffer, size);
if (!ifs) {
	cerr << "Error: only " << ifs.gcount() << " bytes read\n"
		<< "File is " << size << " bytes" << endl;
	return 1;
}
ifs.close();

cv::Mat src_host(4860, 6464, CV_16UC1, buffer);

cout << "buffer to src_host" << endl;

cv::cuda::GpuMat dst, src;
src.upload(src_host);

// uploaded
cout << "Upload to GPU complete" << endl;

// Debayer here
cv::cuda::demosaicing(src, dst, cv::COLOR_BayerRG2BGR);

// done
cout << "Demosaicing complete" << endl;

// have a look
cv::Mat result_host;
dst.download(result_host);

cv::namedWindow("Debayered Image", cv::WINDOW_KEEPRATIO);
cv::resizeWindow("Debayered Image", 4860 / 2, 6464 / 2);
cv::imshow("Debayered Image", result_host);
cv::waitKey(0);

delete[] buffer;
}

```

I get to buffer to src\_host, and as far as I can tell, transfer to the GPU Mat never happens.

Does anyone know what might be happening here? Thanks for any help.

---

<div class="post-metadata">

**Author:** ![jamesyoung](https://avatars.discourse-cdn.com/v4/letter/j/e495f1/32.png) [@jamesyoung](https://forum.opencv.org/u/jamesyoung)\
**Post date:** [February 15, 2021, 5:29am UTC](https://forum.opencv.org/t/demosaicing-a-bayer-image-with-opencv-and-cuda/1329/2 "2021-02-15T05:29:14Z")

</div>

D’oh. I found the image size calculation is wrong, and was being set to zero. It can’t reliably be done with tellg() according to stackoverflow. So I used std::filesystem::file\_size instead.
