2017-02-12 108 views
0

我在OpenCV中編寫了一個簡單的應用程序,用於刪除圖像的黑色背景並以JPG格式保存爲白色背景。但是,它始終以黑色背景保存。無法保存JPG格式的圖像,白色背景OpenCV

這是我的代碼:

Mat Imgsrc = imread("../temp/temp1.jpg",1) ; 
mat dest; 
Mat temp, thr; 

cvtColor(Imgsrc, temp, COLOR_BGR2GRAY); 
threshold(temp,thr, 0, 255, THRESH_BINARY); 

Mat rgb[3]; 
split(Imgsrc,rgb); 

Mat rgba[4] = { rgb[0],rgb[1],rgb[2],thr }; 
merge(rgba,4,dest); 
imwrite("../temp/r5.jpg", dest); 
+1

其保存爲PNG,因爲JPEG圖像不支持透明度。 –

+0

謝謝,但我不想透明我想要白色 – mahdi101

+0

請附上樣品輸入和預期的輸出以及 – ZdaR

回答

1

您可以簡單地使用setTo帶着口罩根據面膜一些像素設定爲一個特定值:

Mat src = imread("../temp/temp1.jpg",1) ; 
Mat dst; 
Mat gray, thr; 

cvtColor(src, gray, COLOR_BGR2GRAY); 

// Are you sure to use 0 as threshold value? 
threshold(gray, thr, 0, 255, THRESH_BINARY); 

// Clone src into dst 
dst = src.clone(); 

// Set to white all pixels that are not zero in the mask 
dst.setTo(Scalar(255,255,255) /*white*/, thr); 

imwrite("../temp/r5.jpg", dst); 

另外幾個注意事項:

  1. 您可以直接使用以下格式將圖像加載爲灰度圖:imread(..., IMREAD_GRAYSCALE);

  2. 您可以避免使用所有那些臨時的Mat s。

  3. 您確定要使用0作爲閾值嗎?因爲在這種情況下,您可以完全避免應用theshold,並將灰度圖像中所有0像素設置爲白色:dst.setTo(Scalar(255,255,255), gray == 0);

這是我會怎麼做:

// Load the image 
Mat src = imread("path/to/img", IMREAD_COLOR); 

// Convert to grayscale 
Mat gray; 
cvtColor(src, gray, COLOR_BGR2GRAY); 

// Set to white all pixels that are 0 in the grayscale image 
src.setTo(Scalar(255,255,255), gray == 0) 

// Save 
imwrite("path/to/other/img", src); 
+0

非常感謝它的工作 – mahdi101