答案 0 :(得分:1)
您遵循以下内容:(描述在代码注释中)
namedWindow("Original_Image", cv::WINDOW_FREERATIO);
namedWindow("Result", cv::WINDOW_FREERATIO);
cv::Mat img = cv::imread("5ZKfM.png");
cv::Mat copy; // this just for showing image
img.copyTo(copy);
// to gray
cv::Mat gray;
cvtColor(img, gray, cv::COLOR_BGR2GRAY);
cv::Mat binaryImg;
// threshold the img to get a binary image
threshold(gray, binaryImg, 80, 255, cv::THRESH_BINARY_INV);
cv::morphologyEx(binaryImg, binaryImg, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5)));
// Floodfill from point (0, 0)
cv::Mat im_floodfill = binaryImg.clone();
cv::floodFill(im_floodfill, cv::Point(0, 0), cv::Scalar(255));
// Invert floodfilled image
cv::Mat im_floodfill_inv;
bitwise_not(im_floodfill, im_floodfill_inv);
// Combine the two images to get the foreground.
cv::bitwise_or(im_floodfill_inv, binaryImg, binaryImg);
// find the contours
std::vector<std::vector<cv::Point> > contours;
cv::findContours(binaryImg, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
// get the largest contoure
cv::Rect rect;
for (std::vector<cv::Point> &contour : contours) {
cv::Rect tempRect = cv::boundingRect(contour);
if(tempRect.area() > rect.area()) {
rect = tempRect;
}
}
// get the sub mat of the picture from the original image
cv::Mat submatOriginal = img(rect);
// prepare the mask
cv::Mat submatBinary = binaryImg(rect);
// remove the picture from the image (set all pixels to white)
submatOriginal.setTo(cv::Scalar(255, 255, 255), submatBinary);
imshow("Result", img);
imshow("Original_Image", copy);
cv::waitKey();
这是结果:
注意:代码是C ++,但是您可以按照以下步骤操作,然后在Python中重新实现。