考虑到可变的结果是我想要裁剪的图片没有黑色部分这是我的代码
cv::Mat result;
result = img1.clone();
cv::warpPerspective(img1, result, H, cv::Size(img1.cols + img2.cols, img1.rows));
Mat gray;
cv::cvtColor(result, gray, COLOR_BGR2GRAY);
Mat thresh;
threshold(result, thresh, 1, 255, THRESH_BINARY);
imshow("r", thresh);
waitKey(0);
int max = 0;
int x = 0;
while (thresh.at<uchar>(x, 10) != 0) {
x++;
if (max < x)
max = x;
//enter code here
}
如何修复我的代码?
这是一般的想法:
0
使用简单的二进制阈值对所有以上阈值进行阈值这是代码,首先,读取图像并将其转换为灰度。threshold
之后简单应用。很简单:
//Read input image:
cv::Mat inputImage = cv::imread( "C://opencvImages//DOrOQ.png", cv::IMREAD_COLOR );
cv::Mat testImage = inputImage.clone(); //Deep copy for cropping
//Convert to greayscale:
cv::cvtColor( inputImage, inputImage, cv::COLOR_BGR2GRAY );
//Threshold everything that is above 0:
cv::Mat binaryMask;
cv::threshold( inputImage, binaryMask, 1, 255, cv::THRESH_BINARY_INV );
这是您获得的二进制掩码:
现在,检查一下幸存下来的小像素。如果可以申请Eroding
,我们可以摆脱这些,其次是Dilating
。我使用的structuring element
是大小3
和5
操作迭代的矩形:
//Clean the mask via Erode + Dilate:
cv::Mat SE = cv::getStructuringElement( cv::MORPH_RECT, cv::Size(3,3) );
int opIterations = 5;
cv::morphologyEx( binaryMask, binaryMask, cv::MORPH_ERODE, SE, cv::Point(-1,-1), opIterations );
cv::morphologyEx( binaryMask, binaryMask, cv::MORPH_DILATE, SE, cv::Point(-1,-1), opIterations );
生成的经过过滤的二进制掩码是这样的:
现在,反转图像,以使最大的白色斑点成为实际的滤波斑点。让我们在此图像上找到最大的轮廓:
//Invert Mask:
binaryMask = 255 - binaryMask;
//Lets get the blob contour:
std::vector< std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours( binaryMask, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
int largestBlobIndex = 0;
double largestArea = 0.0;
//Find the largest blob adn get the outer contour:
for( int i = 0; i < (int)contours.size(); i++ ) {
//Find the area of the contour
double a = cv::contourArea( contours[i], false);
//Store the index of largest contour:
if( a > largestArea ){
largestArea = a;
largestBlobIndex = i;
}
}
//Get the bounding box of the biggest blob:
cv::Rect boundingBox = cv::boundingRect( contours[largestBlobIndex] );
此边界框(红色矩形)包围了您要裁剪的实际区域:
现在,只需裁剪图像:
//Crop the image:
cv::Mat croppedImage = testImage( boundingBox );
然后您得到最终结果:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句