Python3/OpenCV/HoughCircleTransfer Sample


 #smarties16.png

#smarties16A14.png



















from matplotlib import pyplot as plt
import sys
import cv2 as cv
import numpy as np
def main(argv,h):
    #k=argv[1] if len(argv[1])>0 else '*'
    print('argv,h====',argv,h)
    default_file = 'smarties.png' #'smarties.png'
    filename = argv if len(argv[0]) > 0 else default_file

    #filename=default_file
    print("Reading image...",filename,'&\r\n performing CV2.HoughCircle...\n')
    #print('filename.....'+filename+'+++++argv[0]='+argv[0],'default_file='+default_file)
    #print("111111A",filename)

    # Loads an image
    #src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_COLOR)
    src = cv.imread(filename)#, cv.IMREAD_COLOR)
    # Check if image is loaded fine
    if src is None:
        print ('*Error* opening image failure!...[filename='+filename+',argv='+ argv +']')
        print ('Usage: hough_circle.py [image_name('+filename+') -- default [' + default_file + '] \n')
        return -9
    else:
        #print("2222222")
        #cv.imshow('my image',src)
        plt.imshow(src)
        cv.imwrite('smarties#output.png',src) #'smarties.png',src)
        #print("2222222A")
    #print("333333333333")
    #return -8
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
    gray = cv.medianBlur(gray, 5)
    rows = gray.shape[0]
    circles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 1, rows / 8,
                               param1=100, param2=30,
                               minRadius=1, maxRadius=30)
    #return -99
    if circles is not None:
        circles = np.uint16(np.around(circles))
        cc=1
        for i in circles[0, :]:
            center = (i[0], i[1])
            x=i[0]
            y=i[1]
            radius = i[2]
            print(cc,i[0],i[1],'r='+str(radius)) #,'rows='+str(rows))
            if cc>h :
                continue
            # circle center
            cv.circle(src, center, 2, (255, 255, 0), 3)

            # circle outline/contour
            cv.putText(src,'#'+str(cc), (x-10,y), \
              cv.FONT_HERSHEY_COMPLEX, 0.5, (0, 255, 255), 1,\
              cv.LINE_AA)
            cv.circle(src, center, radius, (0, 0, 255), 2)
            cc += 1
    #cv.imshow("detected circles", src)
    plt.imshow(src)
    cv.imwrite('smarties16A'+str(h)+'.png',src) #'smarties.png',src)
    cv.waitKey(0)
    return

main\
('smarties16.png',14)

留言

這個網誌中的熱門文章

Regular Expression

Regular Expression 2019/02/21