C ++以像素方式创建和保存OpenCV 16位图像

时间:2014-06-26 08:59:28

标签: c++ opencv

我想通过手动设置像素值来生成噪声,用OpenCV创建一个16位PNG图像。我尝试了以下方法:

cv::Mat img16(WINDOW_Y, WINDOW_X, CV_16UC3); // create 16 bit mat

float val, new_value;
float noise = 3.1343; // actually randomly generated by randomizer in (0..255)
for (int x = 0; x < WINDOW_X; x++) {
    for (int y = 0; y < WINDOW_Y; y++) {
        for (int i = 0; i < 3; i++) {
            // get value from another CV_8UC3-mat
            val = img.at<cv::Vec3b>(y,x)[i]; 
            // add up noise and scale to 16bit
            new_value = (val + noise)*255; 
            // avoid overflow at 2^16-1
            if (new_value > 65535) { 
                new_value = 65535;
            }
            // set the value to 16bit mat
            img16.at<cv::Vec3s>(y,x)[i] = (short) new_value;
        }
    }
}
// write to PNG file, since PNG supports 16 bit
cv::imwrite(file + ".png", img16);

我得到的输出似乎是16位:

 $ identify output.png 
 output.png PNG 128x128 128x128+0+0 16-bit PseudoClass 65536c

但它显示单调灰色(#808080),而我期待异构图像。它出什么问题了?

1 个答案:

答案 0 :(得分:0)

每当你看到自己在opencv中编写每像素循环时, - 保持,并试图找到内置的东西。

Mat ocv=Mat(200,200,CV_16UC3); // as you can only save 16bit *unsigned* as png or tif
theRNG().fill(ocv,RNG::UNIFORM,0,65535);

enter image description here