6

I have an image I am trying to segment by colouring each pixel either red green or blue. I have calculated a confidence score for each pixel and want to adjust the alpha transparency of the pixel to reflect confidence, i.e. low confidence means almost transparent. Is there a way to do this in OpenCV? If not can anyone suggest a minimally invasive library (C++)?

I have tries using a 4 channel 8-bit Mat as suggested by Aurellius, here is the code:

cv::Mat m = cv::Mat(20,20, CV_8UC4);
    for(int i = 0; i < m.rows; i++){
        for(int j = 0; j < m.cols; j++){
            Vec4b& v = m.at<Vec4b>(i,j);
            v[0] = 255;
            v[1] = 0;
            v[2] = 0;
            v[3] = 0.5;
        }
    }

    imwrite("alpha.png", m);
    namedWindow("m");
    imshow("m", m);
    waitKey(0);

The image shown is just all blue (no transparency) and the image just fully transparent.

4

2 回答 2

5

有很多方法可以做到这一点。一种可能的方法是访问和修改每个单独的像素。假设image是一个四通道、8 位cv::Mat

auto& pixel = image.at<cv::Vec4b>(i,j);
pixel[3] = confidence;

其中ij是图像中像素的索引。

还有其他可能更优雅的方法,但它们将取决于您当前的代码。

更新: 您描述的行为是可以预料的。显然 cv::imshow()不支持透明度。这解释了为什么您显示的图像都是蓝色的。

至于保存的图像,重要的是要记住图像的类型是CV_8UC4。这意味着每个通道元素都存储为uchar. 分配一个值0.5将截断为零,因此保存的图像是完全透明的。

如果您的置信度是 range 中的浮点值,请将[0,1]其缩放 255 以将其置于 8 位图像支持的范围内。因此,

v[3] = 0.5;

变成

v[3] = 0.5 * 255;
于 2013-04-24T15:56:31.890 回答
3

我也遇到了同样的问题,但是什么时候绘制透明形状并通过混合图像来解决它。我在 OpenCV 的文档中找到了这个

if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image.

为此,我建议您查看文档文章。希望这会有所帮助。

于 2013-04-26T10:52:28.147 回答