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

How to change png transprant layer to white in JavaCV

我有一个使用 JavaCV 调整图像大小的代码,我需要将图像透明背景区域更改为白色。 这是我的代码,我尝试将 cvtColor() 与 COLOR_RGBA2RGB 或 COLOR_BGRA2BGR 一起使用,但结果是带有黑色背景的 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);
}

您需要将 RGB 颜色设置为白色,即将 RGB 通道设置为 255,其中 alpha 假设为 0(透明)

此答案基于:

// 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;

你可以在这里测试上面的代码:http://www.techep.csi.cuny.edu/~zhangs/cv.html

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

Mat inImg = imdecode(new Mat(imageData),IMREAD_UNCHANGED);
Mat outImg = Mat.zeros(inImg.size(), CV_8UC3).asMat();

UByteIndexer inIndexer = inImg.createIndexer();
UByteIndexer outIndexer = outImg.createIndexer();

for (int i = 0; i < inIndexer.rows(); i++) {
    for (int j = 0; j < inIndexer.cols(); i++) {
        int[] pixel = new int[4];
        try {
            inIndexer.get(i, j, pixel);
            if (pixel[3] == 0) { // transparency
                pixel[0] = pixel[1] = pixel[2] = 255;
            }
            outIndexer.put(i, j, pixel);
        } catch (IndexOutOfBoundsException e) {

        }
    }
}