OpenCV: how to set alpha transparency of a pixel

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

I am trying to use 4-channel 8-bit Matas Aurellius suggests, 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 displayed image is just blue (no transparency), and the image is just completely transparent.

+5
source share
2 answers

. - . , image 8- cv::Mat:

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

i j - .

, , , , .

UPDATE: , , . - cv::imshow() . , .

, , CV_8UC4. , uchar. 0.5 , , .

float [0,1], 255, , 8- . ,

v[3] = 0.5;

v[3] = 0.5 * 255;
+5

, , . 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.

. , .

+3

All Articles