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

标签 image opencv png transparency 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 颜色设置为白色,即设置 R , G , B channel 至255在哪里 alpha假设为 0(透明)

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

// 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) {

        }
    }
}

关于image - 如何在JavaCV中将png透明层更改为白色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46596381/

相关文章:

php - "Tie"已上传图片至其余部分

c - 使用矩阵进行图像卷积(边缘检测)

php - 我能否以编程方式确定 PNG 是否为动画?

python - 有没有更快的方法将 2d numpy 数组保存到 png

colors - 如何轻松更改PNG图像的颜色?

image - PrimeFaces imageCropper 不显示可选区域

asp.net-mvc-3 - 如何在MVC 3 RAZOR中动态设置图像路径

opencv - 使用RANSAC查找正确的点匹配

python - TypeError : 'NoneType' object is unsubscriptable in cv2. 归一化

c++ - 使用 C++ 进行图像处理还是继续使用 OpenCV?