Home > Software engineering >  could not broadcast input array from shape (512,512) into shape (512,512,2)
could not broadcast input array from shape (512,512) into shape (512,512,2)

Time:06-23

class DataGenerator(Sequence):

 
    def __getitem__(self, index):

        indexes = self.indexes[index * self.batch_size:(index   1) * self.batch_size]

        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        X,y= self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):

        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):

        X = np.empty((self.batch_size, self.dim[0], self.dim[1], self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        for i, ID in enumerate(list_IDs_temp):
           X[i,] = self.load_dicom_xray(self.image_path[ID])

           y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

    def load_dicom_xray(self, path):
        data = pydicom.read_file(path).pixel_array
        if data.mean() == 0:
            return data 
        data = data - np.min(data)
        data = data / np.max(data)
        data = (data * 255).astype(np.uint8)
        return data



training_gen = DataGenerator(index,train_df['Sınıf'],dim=(512,512),n_channels=2,n_classes=10,batch_size=64,shuffle=True,image_path=paths)


Hi, this my code and I'm getting the this error "ValueError: could not broadcast input array from shape (512,512) into shape (512,512,2)". I don't understand why I am getting such an error. I looked on the internet how to fix it, but I couldn't solve it somehow.

Can someone help me here?


/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     65     except Exception as e:  # pylint: disable=broad-except
     66       filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67       raise e.with_traceback(filtered_tb) from None
     68     finally:
     69       del filtered_tb

<ipython-input-13-41198dad25ab> in __data_generation(self, list_IDs_temp)
     39 
     40         for i, ID in enumerate(list_IDs_temp):
---> 41            X[i,] = self.load_dicom_xray(self.image_path[ID])

ValueError: could not broadcast input array from shape (512,512) into shape (512,512,2)

CodePudding user response:

Pydicom.read_file(path).pixel_array returns an array of size image heigt x image width, it does not include any channels. An array with the same shape is returned by self.load_dicom_xray. When trying to put this array into array X, which shape includes channels, this obviously gives an error because the shapes don't match.

Therefore, the shape of X should not include the channels, making its definition become the following:

X = np.empty((self.batch_size, self.dim[0], self.dim[1]))
  • Related