如何在JavaCV中将png transprant层更改为白色

时间:2017-10-05 23:54:30

标签: image opencv png transparency javacv

我有一个使用JavaCV调整图像大小的代码,我需要将图像透明背景区域更改为白色。 这是我的代码,我尝试使用带有COLOR_RGBA2RGB或COLOR_BGRA2BGR的cvtColor(),但结果是带有黑色背景的image。 任何想法?

void myFnc(byte[] imageData){
        Mat img = imdecode(new Mat(imageData),IMREAD_UNCHANGED);
        Size size = new Size(newWidth, newHeight);
        Mat whbkImg = new Mat();
        cvtColor(img, whbkImg, COLOR_BGRA2BGR);
        Mat destImg = new Mat();
        resize(whbkImg,destImg,size);

        IntBuffer param = IntBuffer.allocate(6);
        param.put(CV_IMWRITE_PNG_COMPRESSION);
        param.put(1);
        param.put(CV_IMWRITE_JPEG_QUALITY);
        param.put(100);
        imwrite(filePath, destImg, param);
}

1 个答案:

答案 0 :(得分:1)

您需要将RGB颜色设置为白色,即将<select class="filter"></select>RG频道设置为B,其中255假设为0 (透明)

此答案基于:Change all white pixels of image to transparent in OpenCV C++

alpha

您可以在此处测试上述代码:http://www.techep.csi.cuny.edu/~zhangs/cv.html

对于javacv,下面的代码是等效的(我还没有测试过)

// load image and convert to transparent to white  
Mat inImg = imread(argv[1], IMREAD_UNCHANGED);
if (inImg.empty())
{
    cout << "Error: cannot load source image!\n";
    return -1;
}

imshow ("Input Image", inImg);

Mat outImg = Mat::zeros( inImg.size(), inImg.type() );

for( int y = 0; y < inImg.rows; y++ ) {
    for( int x = 0; x < inImg.cols; x++ ) {
        cv::Vec4b &pixel = inImg.at<cv::Vec4b>(y, x);
        if (pixel[3] < 0.001) { // transparency threshold: 0.1% 
          pixel[0] = pixel[1] = pixel[2] = 255;
        }
        outImg.at<cv::Vec4b>(y,x) = pixel;
    }
}

imshow("Output Image", outImg);

return 0;