Opencv第五课--直线检测和圆检测

作者: 计算机视觉__掉队选手 | 来源:发表于2019-02-02 11:00 被阅读57次

    直线检测

    直线检测通常会用到Hough变换,原理可参考:
    https://www.cnblogs.com/AndyJee/p/3805594.html
    用到的API是cv2.HoughLines和cv2.HoughLinesP
    简单例子

    import cv2
    import numpy as np
    img =cv2.imread("lines.jpg")
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray,50,120)
    minLineLength = 20
    maxLineGap = 5
    lines = cv2.HoughLinesP(edges,1,np.pi/180,20,minLineLength,maxLineGap)
    for x1,y1,x2,y2 in lines[0]:
        cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
    cv2.imshow("edges",edges)
    cv2.imshow("lines",img)
    cv2.waitKey()
    cv2.destroyAllWindows()
    
    image.png
    image.png

    圆检测

    同样使用hough变换,API为cv2.HoughCircles

    import cv2
    import numpy as np
    
    planets = cv2.imread('planet_glow.jpg')
    gray_img = cv2.cvtColor(planets, cv2.COLOR_BGR2GRAY)
    img = cv2.medianBlur(gray_img, 5)
    cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
    
    circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,
                                param1=100,param2=30,minRadius=0,maxRadius=0)
    
    circles = np.uint16(np.around(circles))
    
    for i in circles[0,:]:
        # draw the outer circle
        cv2.circle(planets,(i[0],i[1]),i[2],(0,255,0),2)
        # draw the center of the circle
        cv2.circle(planets,(i[0],i[1]),2,(0,0,255),3)
    
    cv2.imwrite("planets_circles.jpg", planets)
    cv2.imshow("HoughCirlces", planets)
    cv2.waitKey()
    cv2.destroyAllWindows()
    
    
    image.png

    相关文章

      网友评论

        本文标题:Opencv第五课--直线检测和圆检测

        本文链接:https://www.haomeiwen.com/subject/sxkssqtx.html