我必须从图像中提取对象。所以我使用其中一个网站中的下面的代码来提取对象。但输出不合适。下面是示例输入和输出图像。
#include "cv.h"
#include "highgui.h"
using namespace cv;
using namespace std;
int main() {
Mat img0 = imread("/home/user/Pictures/check2.JPG", 1);
Mat img1;
cvtColor(img0, img1, CV_RGB2GRAY);
// apply your filter
Canny(img1, img1, 100, 200);
// find the contours
vector< vector<Point> > contours;
findContours(img1, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
// you could also reuse img1 here
Mat mask = Mat::zeros(img1.rows, img1.cols, CV_8UC1);
// CV_FILLED fills the connected components found
drawContours(mask, contours, -1, Scalar(255), CV_FILLED);
// let's create a new image now
Mat crop(img0.rows, img0.cols, CV_8UC3);
// set background to black
crop.setTo(Scalar(0,0,0));
// and copy
img0.copyTo(crop, mask);
// normalize so imwrite(...)/imshow(...) shows the mask correctly!
normalize(mask.clone(), mask, 0.0, 255.0, CV_MINMAX, CV_8UC1);
// show the images
imshow("cropped", crop);
imwrite("/home/user/Pictures/check1_cropped.JPG", crop);
waitKey();
return 0;
}
预期输出是仅在黑色背景(或指定的任何其他颜色)中获得播放器,但此处输出与黑色重叠。我希望裁剪的球员在黑色背景上。有没有办法实现这个目标?