Opencv imwrite saving white jpeg images

Hello,

I am trying to save images as JPEG, but OpenCV 4.5.2 (built with Turbo JPEG from source) is saving all-white images. I can never make out any detail. Writing PNG files works fine. Does anyone know what might be going wrong with writing JPEG files?

My raw image data is coming from a Mat structure, it’s 16bit unsigned (should be ok for jpeg)

// Support for writing JPG
vector<int> compression_params;
            compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
compression_params.push_back(100);

fs::path output_jpeg = fs::path("C:/images") / fs::path("image.jpg");

bool canwritejpg = cv::haveImageWriter(output_jpeg.filename().string());

// snip


// always gives a white image when trying to output jpeg,
// saving a png works fine though
bool rc = cv::imwrite(output_jpeg.string(), im, compression_params);

I solved the problem by using cv::normalize() to adjust the 12-bit data (stored in 16-bit short integers) down to 8 bit bytes, then the exporting worked fine.