如何在JavaCV中将png传输层更改为白色
我有一个代码来使用JavaCV调整图像大小,我需要将图像透明背景区域更改为白色。 这里是我的代码,我试着用COLOR_RGBA2RGB或COLOR_BGRA2BGR使用cvtColor(),但结果是带有黑色背景的image。 有什么想法?如何在JavaCV中将png传输层更改为白色
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
通道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) {
}
}
}
德您好,感谢的解决方案,这是工作但我想知道是否有一个更好的方式来表现它的性能? – Reza
我们可能需要将像素设置为WHITE,因为我们无法确定透明像素是否为白色,我们可以吗? (透明像素可以是任何颜色,但仍然透明,对吗?) –
发布图片,请 – Silencer
我把图像的URL文本 – Reza