简体   繁体   English

如何在python中访问opencv轮廓点索引?

[英]How to access opencv contour point indexes in python?

Is there way to access the contour[i][j] in python? 有没有办法访问python中的contour[i][j]

I am struggling to translate this c++ into python, because the data structures are different. 我正在努力将这个c ++翻译成python,因为数据结构不同。 It's being hard making comparisions 这很难进行比较

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);
            }
        }
    }
}

Thank you for the patient and answers. 谢谢你的耐心和答案。

OpenCV Python findCountours can be used like this 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

That's what you need 这就是你所需要的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM