Ask Your Question

Revision history [back]

What you have to do are these steps (@Witek his answer cuts off parts of the image, what you want to avoid)

  • Start by converting your image from BGR to BGRA using cvtColor which adds an alpha channels and which is read as transparancy in *.png images.
  • Find all pixels that have a fixed black color (which will almost never happen in natural images) and use those pixels to set their value in the alpha channel to 0.

The code below does this for white pixels, but can be easily switched.

// load as color image BGR
cv::Mat input = cv::imread("your image - can also be your image from the stitching result");

cv::Mat input_bgra;
cv::cvtColor(input, input_bgra, CV_BGR2BGRA);

// find all white pixel and set alpha value to zero:
for (int y = 0; y < input_bgra.rows; ++y)
for (int x = 0; x < input_bgra.cols; ++x)
{
    cv::Vec4b & pixel = input_bgra.at<cv::Vec4b>(y, x);
    // if pixel is white
    if (pixel[0] == 255 && pixel[1] == 255 && pixel[2] == 255)
    {
        // set alpha to zero:
        pixel[3] = 0;
    }
}

// save as .png file (which supports alpha channels/transparency)
cv::imwrite("choose the location to store the image", input_bgra);