我有一个列表,每次运行我的程序时都会复制它自己或附加它自己,但我真的不明白(带opencv的python)

2024-06-16 11:19:08 发布

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

实际上,我正在使用CSRT跟踪器用Opencv编写一个多跟踪器。(我使用了一个在线代码,并根据需要对其进行了修改,源代码如下:https://learnopencv.com/multitracker-multiple-object-tracking-using-opencv-c-python/) 每次“更新”边界框时,其坐标都会添加到列表中

对于每个bbox(边界框),我必须列出一个列表,一个用于bbox左上角的x和y坐标,另一个用于右下角的x和y坐标。(这些列表分别称为p1和p2。)

我已经做了几乎所有我想做的事情,但是bbox1的p2列表并没有停止复制自己或者类似于第三个bbox的p2列表中的内容,而且这并不取决于bbox的存在量。 请注意,我不想要任何关于改进或优化它的评论,我不在乎。 还要注意的是,该程序被设置为最多运行6bbox,这是正常的,我不需要更多,但该程序可以运行1,2,或至少是6bbox,如果我想要的话

如果我幸运的话,这是一个愚蠢的错误,但我不能得到它,所以从其他人的角度来看,可能会发现它比我更好

这是我漫长的、未优化的、丑陋的计划!(如果你能帮助我,谢谢你!)

from __future__ import print_function
import sys
import cv2
import time
from random import randint


#here we're asking data to calculate the number of frames the program will have to show while measuring bounding boxes coordinates and mensuration
framespersecond = int(input("Please enter the framerate of your video/camera per second (without unities please):"))
time.sleep(0.5)
print("Thanks.")
time.sleep(0.5)
timeplayed = int(input("Now, please enter the time you want it to run:(If you wont run a certain amount of time, please enter 0.)"))
if timeplayed == 0:
    time.sleep(0.5)
    numbofframes = int(input("Oh. Please enter the number of frames you want to play:"))
else:
    numbofframes = timeplayed*framespersecond

#we create some of the lists we'll need, the first one to know how much bounding boxes were created and the others for coordinates
bboxnumber = 0
bboxescoord1p1 = []
bboxescoord1p2 = []
bboxescoord2p1 = []
bboxescoord2p2 = []
bboxescoord3p1 = []
bboxescoord3p2 = []
bboxescoord4p1 = []
bboxescoord4p2 = []
bboxescoord5p1 = []
bboxescoord5p2 = []
bboxescoord6p1 = []
bboxescoord6p2 = []

#this timer is for when we use the 'camera' calculation method instead of the video calculation method
#time.sleep(5)

# Set video to load
videoPath = "python-bouncing-ball-simulator-5_V9F95rFx_JQ0y(1).mp4"
#0=intérieure 1=extérieure
#videoPath = 0

# Create a video capture object to read videos
cap = cv2.VideoCapture(videoPath)

# Read first frame
success, frame = cap.read()
# quit if unable to read the video file
if not success:
    print('Failed to read video')
    sys.exit(1)

trackerTypes = ['BOOSTING', 'MIL', 'KCF','TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']
def createTrackerByName(trackerType):
    # Create a tracker based on tracker name
    if trackerType == trackerTypes[0]:
        tracker = cv2.legacy.TrackerBoosting_create()
    elif trackerType == trackerTypes[1]:
        tracker = cv2.legacy.TrackerMIL_create()
    elif trackerType == trackerTypes[2]:
        tracker = cv2.legacy.TrackerKCF_create()
    elif trackerType == trackerTypes[3]:
        tracker = cv2.legacy.TrackerTLD_create()
    elif trackerType == trackerTypes[4]:
        tracker = cv2.legacy.TrackerMedianFlow_create()
    elif trackerType == trackerTypes[5]:
        tracker = cv2.legacy.TrackerGOTURN_create()
    elif trackerType == trackerTypes[6]:
        tracker = cv2.legacy.TrackerMOSSE_create()
    elif trackerType == trackerTypes[7]:
        tracker = cv2.legacy.TrackerCSRT_create()
    else:
        tracker = None
        print('Incorrect tracker name')
        print('Available trackers are:')
        for t in trackerTypes:
            print(t)

    return tracker

## Select boxes
bboxes = []
colors = [] 

# OpenCV's selectROI function doesn't work for selecting multiple objects in Python
# So we will call this function in a loop till we are done selecting all objects
while True:
  # draw bounding boxes over objects
  # selectROI's default behavior is to draw box starting from the center
  # when fromCenter is set to false, you can draw box starting from top left corner
  bbox = cv2.selectROI('MultiTracker', frame)
  bboxes.append(bbox)
  bboxnumber +=1
  colors.append((randint(0, 255), randint(0, 255), randint(0, 255)))
  print("Press q to quit selecting boxes and start tracking")
  print("Press any other key to select next object")
  k = cv2.waitKey(0) & 0xFF
  if (k == 113):  # q is pressed
        print(f"\n\n\n\n\n\n\n\n\n\n")
        break

print('Selected bounding boxes {}'.format(bboxes))



# Specify the tracker type
trackerType = "CSRT"        

# Create MultiTracker object
multiTracker = cv2.legacy.MultiTracker_create()

# Initialize MultiTracker
for bbox in bboxes:
    multiTracker.add(createTrackerByName(trackerType), frame, bbox)

whereami = 1
whereamitot= 0
    # Process video and track objects
for i in range(numbofframes):
    success, frame = cap.read()
    if not success:
        break

    # get updated location of objects in subsequent frames
    success, boxes = multiTracker.update(frame)

    # draw tracked objects
    for i, newbox in enumerate(boxes):
        whereamitot+=1
        p1 = (int(newbox[0]), int(newbox[1]))
        p2 = (int(newbox[0] + newbox[2]), int(newbox[1] + newbox[3]))
        cv2.rectangle(frame, p1, p2, colors[i], 2, 1)

        #define in which list we will put data depending on which bounding box we are 'looking' at
        #p1 are the coordinates of the top left corner and p2 the coordinates of the the bottom right corner
        if whereami ==1:
            bboxescoord1p1.append(p1)
            bboxescoord1p2.append(p2)
            print("---------------------------------")
        elif whereami ==2:
            bboxescoord2p1.append(p1)
            bboxescoord2p2.append(p2)
            print("SHEEEEEEEEEEEEEEEEEEEEEEEEEEEEESsh")
        elif whereami ==3:
            print("lblblbl")
            bboxescoord3p1.append(p1)
            bboxescoord3p2.append(p2)
        elif whereami ==4:
            bboxescoord4p1.append(p1)
            bboxescoord4p2.append(p2)
        elif whereami ==5:
            bboxescoord5p1.append(p1)
            bboxescoord5p2.append(p2)
        elif whereami ==6:
            bboxescoord6p1.append(p1)
            bboxescoord6p2.append(p2)

        #define next lists to fill with data depending of the number of bounding boxes and depending of where in the list list we already are (this is not optimized but who cares?)
        if bboxnumber ==1:
            whereami =1
        elif bboxnumber ==2:
            if whereami == 1:
                whereami+=1
            elif whereami==2:
                whereami=1
            else:
                print("Error in the whereami 2nd section.")
        elif bboxnumber==3:
            if whereami<3:
                whereami+=1
            elif whereami==3:
                whereami=1
            else:
                print("Error in the whereami 3nd section.")
        elif bboxnumber==4:
            if whereami<4:
                whereami+=1
            elif whereami==4:
                whereami=1
            else:
                print("Error in the whereami 4th section.")
        elif bboxnumber==5:
            if whereami<5:
                whereami+=1
            elif whereami==5:
                whereami=1
            else:
                print("Error in the whereami 5th section.")
        elif bboxnumber==6:
            if whereami<6:
                whereami+=1
            elif whereami==6:
                whereami=1
            else:
                print("Error in the whereami 6th section.")
        else:
            print("Error in the 'whereami/bboxnumber' section.")
        


    
    # show frame
    cv2.imshow('MultiTracker', frame)
    

    # quit on ESC button
    if cv2.waitKey(1) == 27:    # esc pressed
        print(bboxescoord)
        index = 0
        cap.release()

datatotnumber = whereamitot
datanumber = datatotnumber/bboxnumber
print(f"\nNUMBER OF FRAMES : {numbofframes}")
print(f"DATA MANIPULATED :{datatotnumber}")
print(f"\np1 is the list of the coordinates of the top left corner, and p2 is the width and height.")
print(f"\n\nDATA\n\n")


if bboxnumber==1:
    print(f"1:\n\np1:{bboxescoord1p1}\n\np2:{bboxescoord1p2}\n\n\n")
elif bboxnumber==2:
    print(f"1:\n\np1:{bboxescoord1p1}\n\np2:{bboxescoord1p2}\n\n\n")
    print(f"2:\n\np1:{bboxescoord2p1}\n\np2:{bboxescoord2p2}\n\n\n")
elif bboxnumber ==3:
    print(f"1:\n\np1:{bboxescoord1p1}\n\np2:{bboxescoord1p2}\n\n\n")
    print(f"2:\n\np1:{bboxescoord2p1}\n\np2:{bboxescoord2p2}\n\n\n")
    print(f"3:\n\np1:{bboxescoord3p1}\n\np2:{bboxescoord1p2}\n\n\n")
elif bboxnumber==4:
    print(f"1:\n\np1:{bboxescoord1p1}\n\np2:{bboxescoord1p2}\n\n\n")
    print(f"2:\n\np1:{bboxescoord2p1}\n\np2:{bboxescoord2p2}\n\n\n")
    print(f"3:\n\np1:{bboxescoord3p1}\n\np2:{bboxescoord1p2}\n\n\n")
    print(f"4:\n\np1:{bboxescoord4p1}\n\np2:{bboxescoord4p2}\n\n\n")
elif bboxnumber==5:
    print(f"1:\n\np1:{bboxescoord1p1}\n\np2:{bboxescoord1p2}\n\n\n")
    print(f"2:\n\np1:{bboxescoord2p1}\n\np2:{bboxescoord2p2}\n\n\n")
    print(f"3:\n\np1:{bboxescoord3p1}\n\np2:{bboxescoord1p2}\n\n\n")
    print(f"4:\n\np1:{bboxescoord4p1}\n\np2:{bboxescoord4p2}\n\n\n")
    print(f"5:\n\np1:{bboxescoord5p1}\n\np2:{bboxescoord5p2}\n\n\n")
elif bboxnumber==6:
    print(f"1:\n\np1:{bboxescoord1p1}\n\np2:{bboxescoord1p2}\n\n\n")
    print(f"2:\n\np1:{bboxescoord2p1}\n\np2:{bboxescoord2p2}\n\n\n")
    print(f"3:\n\np1:{bboxescoord3p1}\n\np2:{bboxescoord1p2}\n\n\n")
    print(f"4:\n\np1:{bboxescoord4p1}\n\np2:{bboxescoord4p2}\n\n\n")
    print(f"5:\n\np1:{bboxescoord5p1}\n\np2:{bboxescoord5p2}\n\n\n")
    print(f"6:\n\np1:{bboxescoord6p1}\n\np2:{bboxescoord6p2}")
else:
    print ("Can't print the lists blblblblb")

编辑

以下是我从空闲中得到的信息:

DATA


1:

p1:[(538, 534), (541, 543), (544, 553), (546, 562), (544, 554), (541, 546), (539, 538), (536, 530), (534, 522), (531, 514), (528, 507), (526, 500), (524, 492), (521, 485), (518, 477), (516, 469), (516, 469), (513, 462), (511, 455), (508, 448), (506, 441), (503, 435), (501, 428), (498, 421), (496, 415), (494, 408), (494, 402), (493, 397), (493, 392), (491, 386), (490, 380), (490, 374), (489, 369), (488, 364), (487, 358), (486, 353), (486, 348), (484, 344), (484, 339), (483, 334), (482, 330), (481, 324), (480, 319), (480, 315), (478, 311), (478, 307), (477, 303), (476, 298), (475, 294), (474, 290), (471, 284), (470, 278), (466, 271), (469, 266), (470, 263), (471, 259), (474, 256), (475, 252), (476, 249), (476, 245)]

p2:[(561, 560), (564, 569), (567, 579), (569, 588), (567, 580), (564, 572), (562, 564), (559, 556), (557, 548), (554, 540), (551, 533), (549, 526), (547, 518), (544, 511), (541, 503), (539, 495), (539, 495), (536, 488), (534, 481), (531, 474), (529, 467), (526, 461), (524, 454), (521, 447), (519, 441), (517, 434), (517, 428), (516, 423), (516, 418), (514, 412), (513, 406), (513, 400), (512, 395), (511, 390), (510, 384), (509, 379), (509, 374), (507, 370), (507, 365), (506, 360), (505, 356), (504, 350), (503, 345), (503, 341), (501, 337), (501, 333), (500, 329), (499, 324), (498, 320), (497, 316), (494, 310), (493, 304), (489, 297), (492, 292), (493, 289), (494, 285), (497, 282), (498, 278), (499, 275), (499, 271)]



2:

p1:[(436, 539), (436, 548), (434, 558), (434, 567), (433, 576), (432, 585), (431, 595), (430, 586), (429, 578), (429, 570), (428, 561), (427, 553), (426, 545), (425, 536), (424, 528), (423, 520), (424, 520), (423, 512), (422, 503), (422, 496), (421, 488), (420, 480), (419, 473), (418, 465), (417, 458), (416, 451), (415, 443), (414, 436), (413, 429), (413, 422), (412, 416), (411, 408), (411, 401), (410, 394), (409, 388), (408, 382), (407, 376), (406, 369), (405, 362), (404, 356), (403, 350), (403, 344), (402, 339), (401, 333), (400, 327), (400, 321), (398, 316), (398, 310), (397, 305), (396, 301), (398, 296), (401, 292), (403, 288), (406, 284), (408, 280), (411, 277), (413, 273), (416, 269), (418, 266), (420, 262)]

p2:[(456, 553), (456, 562), (454, 572), (454, 581), (453, 590), (452, 599), (451, 609), (450, 600), (449, 592), (449, 584), (448, 575), (447, 567), (446, 559), (445, 550), (444, 542), (443, 534), (444, 534), (443, 526), (442, 517), (442, 510), (441, 502), (440, 494), (439, 487), (438, 479), (437, 472), (436, 465), (435, 457), (434, 450), (433, 443), (433, 436), (432, 430), (431, 422), (431, 415), (430, 408), (429, 402), (428, 396), (427, 390), (426, 383), (425, 376), (424, 370), (423, 364), (423, 358), (422, 353), (421, 347), (420, 341), (420, 335), (418, 330), (418, 324), (417, 319), (416, 315), (418, 310), (421, 306), (423, 302), (426, 298), (428, 294), (431, 291), (433, 287), (436, 283), (438, 280), (440, 276)]



3:

p1:[]

p2:[(561, 560), (564, 569), (567, 579), (569, 588), (567, 580), (564, 572), (562, 564), (559, 556), (557, 548), (554, 540), (551, 533), (549, 526), (547, 518), (544, 511), (541, 503), (539, 495), (539, 495), (536, 488), (534, 481), (531, 474), (529, 467), (526, 461), (524, 454), (521, 447), (519, 441), (517, 434), (517, 428), (516, 423), (516, 418), (514, 412), (513, 406), (513, 400), (512, 395), (511, 390), (510, 384), (509, 379), (509, 374), (507, 370), (507, 365), (506, 360), (505, 356), (504, 350), (503, 345), (503, 341), (501, 337), (501, 333), (500, 329), (499, 324), (498, 320), (497, 316), (494, 310), (493, 304), (489, 297), (492, 292), (493, 289), (494, 285), (497, 282), (498, 278), (499, 275), (499, 271)]

Tags: ofthetoinifcv2trackerprint