您好我正在做一个Android应用程序,它使用OpenCV来检测矩形/正方形,检测它们我正在使用squares.cpp中的函数(修改了一下)。发现我存储在矢量>中的每个方块的点数。正方形,然后我将它传递给选择最大的函数并将其存储在矢量theBiggestSq中。问题在于裁剪功能,我将在下面粘贴代码(我会将链接发布到显示问题的youtube)。如果实际的正方形距离相机足够远,它可以正常工作,但如果我稍微关闭它,它会挂起。我将从LogCat发布问题的打印屏幕,并打印出点(从theBiggestSq矢量获取的边界点,可能有助于找到解决方案)。
void cutAndSave(vector<Point> theBiggestSq, Mat image){
RotatedRect box = minAreaRect(Mat(theBiggestSq));
// Draw bounding box in the original image (debug purposes)
//cv::Point2f vertices[4];
//box.points(vertices);
//for (int i = 0; i < 4; ++i)
//{
//cv::line(img, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0), 1, CV_AA);
//}
//cv::imshow("box", img);
//cv::imwrite("box.png", img);
// Set Region of Interest to the area defined by the box
Rect roi;
roi.x = box.center.x - (box.size.width / 2);
roi.y = box.center.y - (box.size.height / 2);
roi.width = box.size.width;
roi.height = box.size.height;
// Crop the original image to the defined ROI
//bmp=Bitmap.createBitmap(box.size.width / 2, box.size.height / 2, Bitmap.Config.ARGB_8888);
Mat crop = image(roi);
//Mat crop = image(Rect(roi.x, roi.y, roi.width, roi.height)).clone();
//Utils.matToBitmap(crop*.clone()* ,bmp);
imwrite("/sdcard/OpenCVTest/1.png", bmp);
imshow("crop", crop);
}
video of my app and its problems
印刷的绳索分别是:roi.x roi.y roi.width roi.height
另一个问题是绘制的边界应该是绿色,但正如你在视频中看到的那样它们是扭曲的(弯曲就像那些边界是玻璃制成的?)。
感谢您的帮助。我是openCV的新手,只用了一个月,所以请宽容。
编辑: 绘图代码:
//draw//
for( size_t i = 0; i < squares.size(); i++ )
{
const Point* p = &squares[i][0];
int n = (int)squares[i].size();
polylines(mBgra, &p, &n, 1, true, Scalar(255,255,0), 5, 10);
//Rect rect = boundingRect(cv::Mat(squares[i]));
//rectangle(mBgra, rect.tl(), rect.br(), cv::Scalar(0,255,0), 2, 8, 0);
}
答案 0 :(得分:2)
此错误基本上告诉您原因 - 您的投资回报率超出图像尺寸。这意味着当您从Rect roi
中提取RotatedRect box
时,x或y小于零,或宽度/高度将尺寸推到图像外。你应该用
// Propose rectangle from data
int proposedX = box.center.x - (box.size.width / 2);
int proposedY = box.center.y - (box.size.height / 2);
int proposedW = box.size.width;
int proposedH = box.size.height;
// Ensure top-left edge is within image
roi.x = proposedX < 0 ? 0 : proposedX;
roi.y = proposedY < 0 ? 0 : proposedY;
// Ensure bottom-right edge is within image
roi.width =
(roi.x - 1 + proposedW) > image.cols ? // Will this roi exceed image?
(image.cols - 1 - roi.x) // YES: make roi go to image edge
: proposedW; // NO: continue as proposed
// Similar for height
roi.height = (roi.y - 1 + proposedH) > image.rows ? (image.rows - 1 - roi.y) : proposedH;