Home > OS >  Adding np array objects to a list
Adding np array objects to a list

Time:12-13

I am trying to append a sub image which is numpy array objects to a list.

    temp = []
    for color in COLOUR_RANGE:
       #Some code to extract the color region which is represented in numpy 
        if cv2.contourArea(coloured_cnt) > 400:
            
            x, y, w, h = cv2.boundingRect(coloured_cnt)

            coloursRect = cv2.cvtColor(img[y:y h, x:x w], cv2.COLOR_BGR2RGB)
            coloursRect_1D = np.vstack(coloursRect)/255

            temp.append(coloursRect_1D.copy())
            print(len(temp))
            print(type(temp))

But the length of the list is added by two every loop.

2
<class 'list'>
4
<class 'list'>
6
<class 'list'>
8
<class 'list'>
10

However, if i create a new list as follows

    temp = [
        np.vstack(coloursRectList['blue'])/255,
        np.vstack(coloursRectList['green'])/255,
        np.vstack(coloursRectList['yellow'])/255,
        np.vstack(coloursRectList['red'])/255,
        np.vstack(coloursRectList['black'])/255,

    print('len of temp', len(temp))
    print('type of temp', type(temp))

The output is as expected

len of temp 6
type of temp <class 'list'>

I prefer the first method as it would be more dynamic so that I can

EXTRACTED = np.array(np.vstack(temp))

I am wondering how to append numpy object to a list properly. Any help is appreciated.


Code tried to reproduce the error with numpy but it fails to reappear. I am not sure what goes wrong.

import numpy as np

mylist = []
a = np.zeros(shape=(96, 93, 3))
b = np.vstack(a)/255
print(a.shape)
print(type(a))
print(b.shape)
print(type(b))
for i in range(5):
    mylist.append(b.copy())
    print(len(mylist))

Output

(96, 93, 3)
<class 'numpy.ndarray'>
(8928, 3)
<class 'numpy.ndarray'>
1
2
3
4
5

CodePudding user response:

Python list.append() method appends only a single element regardless of its type, it's not possible to get the list length increased by two after a single append call. You must have "temp" changed in another place in the loop, please double-check.

  • Related