jimjammo
jimjammo

Reputation: 51

How can I create a 4D numpy array from images?

I have some images that I'm converting into 3D numpy arrays. I would like to aggregate all of these image arrays into one big numpy array (such that index 0 of this big array is the 3D numpy array representing my image).

What is the best way to do this?

My image shape looks like this:

(128, 128, 3) # shape of each image
[[[119  95  59]
  [118  94  58]
  [120  96  60]
  ...
  [110  89  51]
  [111  89  54]
  [116  93  61]]

 [[136 112  76]
  [139 115  79]
  [141 117  81]
  ...
  [114  93  55]
  [119  97  62]
  [114  91  59]]

 [[127 103  67]
  [127 103  67]
  [134 110  74]
  ...
  [110  89  51]
  [115  93  57]
  [119  97  62]]

 ...

 [[116  92  68]
  [105  83  55]
  [109  87  52]
  ...
  [119  99  58]
  [125 102  64]
  [120  97  59]]

 [[111  90  68]
  [111  89  64]
  [105  84  53]
  ...
  [123 101  60]
  [121  96  56]
  [129 104  64]]

 [[109  90  69]
  [105  85  60]
  [105  84  56]
  ...
  [121  99  58]
  [128 102  62]
  [129 104  62]]]

Upvotes: 5

Views: 5251

Answers (1)

hpaulj
hpaulj

Reputation: 231335

If all the image arrays have the same shape, such as (128, 128, 3), then np.stack will do nicely

np.stack(alist_images, axis=0)

should produce a (n, 128, 128, 3) array.

Actually np.array(alist_images) should also work, but stack lets you pick another axis to join them on, e.g. (128, 128, 3, n)

If it complains about dimensions not matching, then you don't have a list of matching arrays.

Upvotes: 3

Related Questions