Search code examples
listinsertappendcombinations

Insert an element at a specific position in a list at each video frame in python


I am struggling to get a list of 4 elements (so a fixed number of elements) at each frame, if in the detected frame I don't have 2 classes, the fixed list puts 0 to the counter. this is my code :

                count = []
                cc = []

                for c in det[:, 5].unique():
                    n = (det[:, 5] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string
                    count.append(int(n))
                    cc.append(int(c))
                 if cc != 0:
                     count.insert(0, 0) 
                 if cc!= 1:
                     count.insert(1,0) 
                 if cc != 2:
                     count.insert(2, 0)
                 if cc != 3:
                     count.insert(3, 0)
                 print('count', str(count))
                 
        
                print('cc', cc[:])
                print(str(count))
                print(sum(count))
                frames_c_count.append(count)

Here c is a list of not fixed number of elements but the maximum is 4 so cc = [0,1,2,3] when all classes are detected otherwise it is only the number of the detected class! What I am trying to do is to always have a list of 4 elements in count (the sum of the same number of classes), when class 0 is missing I replace the first column with 0, the same thing for the other classes. I do that to be able to sum from a table all rows of all frames at the end of the video.

The problem here is that I have a combination of a lot of elements, if I have 4 classes I think I have 16 possible ways to do the condition, when I put only these conditions (code above) I have for example output for one frame: >>> count [0, 0, 0, 0, 4, 3] in which class 1 and class 3 are detected, but as you can see "4" should be in the 2nd column and "3" should be in the 4th column, so the result I wan is count = [0,4,0,3]. Replacing 0 when the class is not in the cc list. Is there any way to do what I want to do using python functions, loop? Thank you in advance


Solution

  • It may help someone, I figured out the problem by coding these few lines:

             ... ll = []
                L = [0, 0, 0, 0]
                for c in det[:, 5].unique():
                    n = (det[:, 5] == c).sum()  # detections per class
                    l = (int(c), int(n))
                    ll.append(l)
    
                #print('tuple of the class and its total detected number', ll)
                for cl, tot in ll:
                    L[cl] += tot
                print("list of sum of each detected class", L)
                frames_c_count.append(L)...