我是OpenCV和C++的初學者,但現在我必須爲這個問題找到解決方案: 我有一個藍色背景的人的圖像,現在我必須減去背景從圖像,然後將其替換爲另一個圖像。 現在我認爲有2種方法來解決這個問題,但我不知道哪個好:從OpenCV C++減去藍色背景圖像
解決方案1 :
- 圖像轉換到B &W¯¯
- 使用它作爲減去背景的面具。
解決方案2:
- 使用coutour找到後臺,
- ,然後減去它。
我已經作爲解決方案1實施,但結果並非如我所料。 你知道還有另一個更好的解決方案,或者有人已經實現它作爲源代碼? 我會感謝您的幫助。
我在這裏更新我的源代碼,請給我一些意見
//Get the image with person
cv::Mat imgRBG = imread("test.jpg");
//Convert this image to grayscale
cv::Mat imgGray = imread("test.jpg",CV_LOAD_IMAGE_GRAYSCALE);
//Get the background from image
cv::Mat background = imread("paris.jpg");
cv::Mat imgB, imgW;
//Image with black background but inside have some area black
threshold(imgGray, imgB, 200, 255, CV_THRESH_BINARY_INV);
cv::Mat imgTemp;
cv::Mat maskB, maskW;
cv::Mat imgDisplayB, imgDisplayW;
cv::Mat imgDisplay1, imgDisplay2, imgResult;
//Copy image with black background, overide the original image
//Now imgTemp has black background wrap the human image, and inside the person, if there're some white area, they will be replace by black area
imgRBG.copyTo(imgTemp, imgB);
//Now replace the black background with white color
cv::floodFill(imgTemp, cv::Point(imgTemp.cols -10 ,10), cv::Scalar(255.0, 255.0, 255.0));
cv::floodFill(imgTemp, cv::Point(10,10), cv::Scalar(255.0, 255.0, 255.0));
cv::floodFill(imgTemp, cv::Point(10,imgTemp.rows -10), cv::Scalar(255.0, 255.0, 255.0));
cv::floodFill(imgTemp, cv::Point(imgTemp.cols -10,imgTemp.rows -10), cv::Scalar(255.0, 255.0, 255.0));
//Convert to grayscale
cvtColor(imgTemp,imgGray,CV_RGB2GRAY);
//Convert to B&W image, now background is black, other is white
threshold(imgGray, maskB, 200, 255, CV_THRESH_BINARY_INV);
//Convert to B&W image, now background is white, other is black
threshold(imgGray, maskW, 200, 255, CV_THRESH_BINARY);
//Replace background of image by the black mask
imgRBG.copyTo(imgDisplayB, maskB);
//Clone the background image
cv::Mat overlay = background.clone();
//Create ROI
cv::Mat overlayROI = overlay(cv::Rect(0,0,imgDisplayB.cols,imgDisplayB.rows));
//Replace the area which will be human image by white color
overlayROI.copyTo(imgResult, maskW);
//Add the person image
cv::addWeighted(imgResult,1,imgDisplayB,1,0.0,imgResult);
imshow("Image Result", imgResult);
waitKey();
return 0;
嘗試分割。使用cv :: grabCut以及非常接近邊界的前景蒙版(例如,將圖像的4個角點像素設置爲前景蒙版)。 – William
親愛的威廉。你能描述更多細節嗎?如何在這種情況下使用grabCut?謝謝 – user2411800
閱讀[本](http://www.packtpub.com/article/opencv-segmenting-images)並嘗試[this](http://stackoverflow.com/questions/14111716/how-to-set-a -mask圖像換grabcut合的OpenCV)。 – William