我有这张图片:
如何在OpenCv c ++中实现极端点查找器代码,如图所示?
任何人都有任何想法吗?
# determine the most extreme points along the contour
leftmost = tuple(cnt [cnt[:,:,0].argmin()][0]);
rightmost = tuple(cnt [cnt[:,:,0].argmax()][0]);
topmost = tuple(cnt [cnt[:,:,1].argmin()][0]);
bottommost = tuple(cnt [cnt[:,:,1].argmax()][0]);
答案 0 :(得分:3)
假设您已经拥有轮廓并且它是一个点矢量,您可以将std::minmax_element函数用于同一端。它支持一种比较方法,如果它遵循签名,它可以是任何你想要的。所以一个类似于你所做的简单代码:
#include <iostream>
#include <vector>
#include <algorithm>
// this is not necessary, just for testing (OpenCV Points should be used instead)
struct Point
{
int x;
int y;
Point():
x(0), y(0){}
Point(int xVal, int yVal):
x(xVal), y(yVal){}
};
int main()
{
std::vector<Point> cnt = {
{1,2},{4,5},{1,6}, {7,8}, {9,3}, {2,6}
};
// compare x axis
auto val = std::minmax_element(cnt.begin(), cnt.end(), [](Point const& a, Point const& b){
return a.x < b.x;
});
std::cout << " leftMost [ " << val.first->x << ", " << val.first->y << " ]" << std::endl;
std::cout << " RightMost [ " << val.second->x << ", " << val.second->y << " ]" << std::endl;
// compare y axis
val = std::minmax_element(cnt.begin(), cnt.end(), [](Point const& a, Point const& b){
return a.y < b.y;
});
std::cout << " TopMost [ " << val.first->x << ", " << val.first->y << " ]" << std::endl;
std::cout << " BottomMost [ " << val.second->x << ", " << val.second->y << " ]" << std::endl;
return 0;
}
这是运行它的link。
在这个例子中,Point结构只是为了模拟OpenCV,但它的工作方式完全相同。我创建了一个测试向量,运行minmax_element
仅比较x
轴并打印结果。我对y
轴做同样的事情。
此函数向这些对象返回一对迭代器,如果需要返回它们,请确保复制它们:)
答案 1 :(得分:0)
void thresh_callback(int, void* )
{
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Canny( src_gray, canny_output, thresh, thresh*2, 3 );
findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
for( size_t i = 0; i< contours.size(); i++ )
{
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
drawContours( drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point() );
}
namedWindow( "Contours", WINDOW_AUTOSIZE );
imshow( "Contours", drawing );
}
使用此代码上面的代码是如何工作的