Demosaicing a bayer image with OpenCV and CUDA

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.

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.