Opencv算法记录:如何使用Opencv求解圆与轮廓、直线的交点

嵌入式C语言学习进阶系列文章

GUN C编译器拓展语法学习笔记(一)GNU C特殊语法部分详解
GUN C编译器拓展语法学习笔记(二)属性声明
GUN C编译器拓展语法学习笔记(三)内联函数、内建函数与可变参数宏
数组存储与指针学习笔记(一)数据类型与存储、数据对齐、数据移植、typedef


文章目录

  • 嵌入式C语言学习进阶系列文章


  最近涉及到Opencv用来求解轮廓与直线或者圆等规则物体的交点问题,特写下如下文章记录此。简单作出解释:通过创建轮廓与所求图像的掩膜,然后两者通过逻辑与运算得出交点位置。同理,求解两轮廓的交点方式也是一样的。

DEBUG = True
def contourCirclesIntersect(original_image, contour, circles):
    '''
    计算轮廓与内外圆的圆弧以及圆弧的圆心角
        @contour:轮廓数组
        @circles:圆坐标(cx,cy,r)
        return:
        @points:交点数组
        @arc_angle:圆弧圆心角
    '''
    # 获取图像大小
    blank = np.zeros(original_image.shape[0:2])
    # 创建轮廓与圆形的掩膜
    image1 = cv2.drawContours(blank.copy(), contour, -1, 2)
    image2 = cv2.circle(blank.copy(),(circles[0],circles[1]),circles[2],1,2)
    # 逻辑与判断交点
    intersection = np.logical_and(image1, image2)
    # 获得交点位置
    points = np.argwhere(intersection==True)
    if len(points) >= 2: # 找出大于2个交点的领域
        arc_angle = calcArcAngle(original_image,
        center=(circles[0],circles[1]),
        start=(points[0][1],points[0][0]),
        end=(points[-1][1],points[-1][0]),
        radius=circles[2],
        fill=1,
        color=(255,255,0)
        )
    R = circles[2]     
    if DEBUG:
        if len(points):
            cv2.circle(original_image,(points[0][1],points[0][0]),1,(0,255,0),2)
            cv2.circle(original_image,(points[-1][1],points[-1][0]),1,(0,255,0),2)
            cv2.line(original_image,(circles[0],circles[1]),(points[0][1],points[0][0]),(0,255,0),1)
            cv2.line(original_image,(circles[0],circles[1]),(points[-1][1],points[-1][0]),(0,255,0),1)
    return points,arc_angle

def contourLineIntersect(original_image,contour,line_pt):
    '''
        计算轮廓与直线的交点
        @contour:轮廓数组
        @line_pt:直线两点坐标[(x1,y1),(x2,y2)]
        return:
       	@points:交点数组
    '''
    # 获取图像大小
    blank = np.zeros(original_image.shape[0:2])
    # 创建轮廓与直线的掩膜
    image1 = cv2.drawContours(blank.copy(), contour, -1, 2)
    image2 = drawLine(blank.copy(),(line_pt[0][0],line_pt[0][1]),(line_pt[1][0],line_pt[1][1]))
    # 逻辑计算
    intersection = np.logical_and(image1, image2)
    # 获得交点位置
    points = np.argwhere(intersection==True)
    if DEBUG:
        if len(points):
            print('contourLineIntersect:',points)
            cv2.circle(original_image,(points[0][1],points[0][0]),1,(0,255,0),2)
            cv2.circle(original_image,(points[-1][1],points[-1][0]),1,(0,255,0),2)
    return points

你可能感兴趣的:(Opencv计算机视觉,opencv,算法,计算机视觉)