OpenCV: how to set alpha transparency of a pixel

后端 未结 2 1636
北荒
北荒 2020-12-20 21:07

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 tra

相关标签:
2条回答
  • 2020-12-20 21:24

    There are many ways to accomplish this. One possible way is to access and modify each individual pixel. Assuming image is a four-channel, 8-bit cv::Mat:

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

    where i and j are the indices of the pixel in the image.

    There are other methods that are probably more elegant, but they will depend on your current code.

    UPDATE: The behavior you describe is to be expected. Apparently cv::imshow() does not support transparency. This explains why your displayed image is all blue.

    As for the saved image, it is important to remember that the image is of type CV_8UC4. That means that each channel element is stored as a uchar. Assigning a value of 0.5 will truncate to zero, hence the fully transparent saved image.

    If your confidence is a float value in the range [0,1], scale it by 255 to put it in the range supported by 8-bit images. Thus,

    v[3] = 0.5;
    

    becomes

    v[3] = 0.5 * 255;
    
    0 讨论(0)
  • 2020-12-20 21:30

    I've also had the same problem but when was drawing transparent shapes and solved it by blending images. I've fount this in OpenCV's documentation

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

    For this purpose I suggest you to take a look at this documentation article. Hope this will help.

    0 讨论(0)
提交回复
热议问题