由于您是新手,我建议您使用最简单的方法来检测形状对象,例如矩形。首先,您将对分割图像应用阈值处理(您可以使用Canny()),然后使用矩形的findContours() 提取轮廓,最后使用approxPolyDP() - 它将轮廓形状近似为具有较少顶点数的另一个形状,具体取决于我们指定的精度。它是Douglas-Peucker算法的一种实现。
cv::Mat src = ...;
cv::Mat gray = ...;
cv::Mat bw;
cv::Canny(gray, bw, 800, 850, 5, true); // Modify values for your use-case
std::vector<std::vector<cv::Point>> countours;
cv::findContours(bw.clone(), countours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
std::vector<cv::Point> approx;
cv::Mat dst = src.clone();
for(int i = 0; i < countours.size(); i++)
{
cv::approxPolyDP(Mat(countours[i]), approx, arcLength(Mat(countours[i]), true) * 0.01, true);
if (approx.size() == 4)
{
double maxCosine = 0;
for (int j = 2; j < 5; j++)
{
double cosine = fabs(angle(approx[j % 4], approx[j - 2], approx[j - 1]));
maxCosine = MAX(maxCosine, cosine);
}
if (maxCosine < 1.2)
{
cv::line(dst, approx.at(0), approx.at(1), cvScalar(0,0,255), 4);
cv::line(dst, approx.at(1), approx.at(2), cvScalar(0,0,255), 4);
cv::line(dst, approx.at(2), approx.at(3), cvScalar(0,0,255), 4);
cv::line(dst, approx.at(3), approx.at(0), cvScalar(0,0,255), 4);
}
}
}