【问题标题】:How to access opencv contour point indexes in python?如何在python中访问opencv轮廓点索引?
【发布时间】:2015-09-16 11:00:25
【问题描述】:

有没有办法在python中访问contour[i][j]

我正在努力将这个 c++ 翻译成 python,因为数据结构不同。很难比较

static double distanceBtwPoints(const cv::Point a, const cv::Point b)
{
     double xDiff = a.x - b.x;
     double yDiff = a.y - b.y;

     return std::sqrt((xDiff * xDiff) + (yDiff * yDiff));
}

static int findNearestPointIndex(const cv::Point pt, const vector<Point> points)
{
    int nearestpointindex = 0;
    double distance;
    double mindistance = 1e+9;

    for ( size_t i = 0; i < points.size(); i++)
    {
        distance = distanceBtwPoints(pt,points[i]);

        if( distance < mindistance )
        {
            mindistance =  distance;
            nearestpointindex = i;
        }
    }
    return nearestpointindex;
}

int main( int argc, char** argv )
{
    Point pt0;
    int shift=0; // optional value for drawing scaled
    Scalar color = Scalar(0,0,0);

    char* filename = argc >= 2 ? argv[1] : (char*)"test.png";
    Mat img = imread(filename);
    if (img.empty())
        return -1;

    vector<vector<Point> > contours;
    vector<Point> contour;
    findContours( bw, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE );

    contour = contours[0];
    for ( size_t i = 0; i < contours.size(); i++)
    {
        if( contour.size() < contours[i].size() )
            contour = contours[i];
    }

    for ( size_t i = 0; i < contours.size(); i++)
    {
        if( contour != contours[i] && contours[i].size() > 10 )
        {
            for ( size_t j = 0; j <  contours[i].size(); j++)
            {
                pt0 = contours[i][j];
               line(src,pt0,contour[findNearestPointIndex(pt0,contour)],color,1,LINE_8,shift);
            }
        }
    }
}

感谢您的耐心和解答。

【问题讨论】:

标签: python c++ opencv contour


【解决方案1】:

OpenCV Python findCountours可以这样使用

import cv2
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# contours = [array([[[x1,  y1]], ..., [[xn,  yn]]]), array([[[x1,  y1]], ..., [[xn,  yn]]])]
contour = contours[0] # contours[i], where i = index of the contour
# contour = [[[x1,  y1]], [[x2,  y2]], ..., [[xn,  yn]]]
# contour[0] = [[x1,  y1]]
# contour[0][0] = [x1,  y1]
# contour[0][0][0] = x1
# contour[0][0][1] = y1

这就是你需要的

pt0 = contour[i][j][0] # that's what you need to replace pt0 = contours[i][j];
# pt0 = [x, y], where pt0[0] = x, pt0[1] = y

【讨论】:

  • 我怎样才能强加这个条件? :` if( 轮廓 != 轮廓[i] && 轮廓[i].size() > 10 )`
  • contours[i] 是一个 NumPy 数组。要获取它的行数,只需获取contours[i].shape[0]
  • 我的意思是,c++ contours[i].size() == python contours[i].shape[0]。这能回答你的问题吗?
  • And 'if( contour != contours[i] ' ? 正如你在 c++ 代码中看到的那样,if 条件有点棘手。第一部分是关于“验证轮廓不是最大”,第二部分是关于轮廓长度/面积
  • 这个 c++ if 的等价物是 if not np.array_equal(contour, contours[i]) and contours[i].shape[0] &gt; 10:
猜你喜欢
  • 2014-07-12
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 2021-09-07
  • 1970-01-01
  • 2019-10-07
相关资源
最近更新 更多