Search code examples
pythonconcatenationcell-array

Nesting List within a List and Numpy Arrays


How to insert some of the matrices (like images) in each cell of a list or array and then use each of matrices as an array (like cell arrays in Matlab)? I have tried doing it, as in the following code:

    a = []
    for dcmfile in dcmfiles:
        dcm_image = pydicom.dcmread(os.path.join(root, dcmfile))
        a.append([dcm_image.pixel_array])
        volume_image = np.concatenate((a, ?), 1)  # problem is in this line because two variables are needed to the "concatenate".

َAlso, I have checked the below code but it has been had an error:

    volume_image = {}
    for i, dcmfile in dcmfiles:
        dcm_image = pydicom.dcmread(os.path.join(root, dcmfile))
        volume_image[i] = dcm_image.pixel_array

ValueError: too many values to unpack (expected 2)


Solution

  • The error says that at some point, python expects 2 objects (values) but only one is sent. The culprit is in:

    for i, dcmfile in dcmfiles:
    

    Here you are iterating through the elements of dcmfile, therefore the for .. in statement will return one element at time to operate with. However, you are aasking for two elements, namely i and dcmfile, hence the error.

    You should change it with:

    for i, dcmfile in enumerate(dcmfiles):
    

    if dcmfiles is an iterable or in:

    for i, dcmfile in dcmfiles.iteritems(): # for python 2.x
    for i, dcmfile in dcmfiles.items(): # for python 3.x
    

    if dcmfiles is a dictionary