简体   繁体   中英

Converting dictionary to multi-dimensional array?

I have dictionary which stores colored image data for 4 classes. Each image is 256* 256 * 3. My dictionary has 4 keys named plane, bird, dog and cat. Each of this key in the dictionary has 50 arrays of dimension 256* 256* 3 (50 images of each class as an 3-D array, total 200 images). I want to convert this data structure into 200 * 3* 256* 256 shape array which has extracted label from dictionary key. How can I achieve this easiest way? I tried numpy reshape but did not work.

So I'm assuming your data setup looks something like this (obviously with real data instead of random data):

classes = ["plane", "bird", "dog", "cat"]
images = {
     k: [np.random.uniform(size=(256, 256, 3))
         for _ in range(50)]
     for k in classes
}

What we can do is the following:

X = np.concatenate([images[k] for k in classes], axis=0)
y = np.concatenate([[i] * len(images[k]) for i, k in enumerate(classes)])

Which gives what you want, I believe:

>>> X.shape
(200, 256, 256, 3)

>>> y.shape
(200,)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM