2017-10-05 137 views
0

我有一個代碼來使用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); 
} 
+0

發佈圖片,請 – Silencer

+0

我把圖像的URL文本 – Reza

回答

1

您需要將RGB顏色爲白色,即設置RGB通道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) { 

     } 
    } 
} 
+0

德您好,感謝的解決方案,這是工作但我想知道是否有一個更好的方式來表現它的性能? – Reza

+0

我們可能需要將像素設置爲WHITE,因爲我們無法確定透明像素是否爲白色,我們可以嗎? (透明像素可以是任何顏色,但仍然透明,對嗎?) –

相關問題