我怎样才能使我的OpenCV代码工作而不成为stu

2024-04-23 09:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新的程序员,我在OpenCV库(Python代码)的毕业设计中工作

我需要写代码来检测气球在恒定的背景和监测它

我决定使用子结构函数+HoughCircles,问题是每一个代码都工作得很好[除了圆检测工作得不是最好的],当我组合这两个代码时,它工作得非常慢并且粘滞了很多,有人能建议我如何正确插入它,这样它就不会粘滞并且以某种方式改善HoughCircles吗

    import numpy as np
    #import RPi.GPIO as GPIO
    import time
    import cv2

    cap = cv2.VideoCapture(0)
    fgbg = cv2.createBackgroundSubtractorMOG2()

    while True:

        ret, frame = cap.read()

        if frame is None:
            break

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        fgmask = fgbg.apply(gray)

        #changes = sum(sum(fgmask>200))
        changes = (fgmask>200).sum() #
        is_moving = (changes > 10000)
        print(changes, is_moving)



        items = []

        contours, hier = cv2.findContours(fgmask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        for cnt in contours:
            area = cv2.contourArea(cnt)
            if 200 < area:
                (x,y,w,h) = cv2.boundingRect(cnt)
                cv2.rectangle(fgmask, (x,y),(x+w,y+h),255, 2)
                cv2.rectangle(frame, (x,y),(x+w,y+h),(0,255,0), 2)
                items.append( (area, x, y, w, h) )

        if items:
            main_item = max(items)
            area, x, y, w, h = main_item
            if w > h:
                r = w//2
            else:
                r = h//2
            cv2.circle(frame, (x+w//2, y+h//2), r, (0,0,255), 2)
            print(x + w // 2, y + h // 2)

        circles = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,50,
                              param1=50,param2=30,minRadius=0,maxRadius=0)
        #circles = np.uint16(np.around(circles))
        if circles is not None:
            # convert the (x, y) coordinates and radius of the circles to integers
            circles = np.round(circles[0, :]).astype("int")

            # loop over the (x, y) coordinates and radius of the circles
            for (x, y, r) in circles:
                # draw the circle in the output image, then draw a rectangle in the image
                # corresponding to the center of the circle
                cv2.circle(gray, (x, y), r, (0, 255, 0), 4)
                #cv2.rectangle(gray, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
                # time.sleep(0.5)
                print("Column Number: ")
                print(x)
                print("Row Number: ")
                print(y)
                print("Radius is: ")
                print(r)

        cv2.imshow('fgmask', fgmask)
        cv2.imshow('frame', frame)
        cv2.imshow('gray',gray)

        k = cv2.waitKey(10) & 0xff
        if k == 27:
            break

    cv2.destroyAllWindows()
    cap.release()

非常感谢


Tags: the代码inimportifisnpitems