4
\$\begingroup\$

I am trying to write a generic Python script that do the following types of tasks:

  1. Load .npy file (the .npy file is of shape (m_samples, channels, row, column), which corresponds tom_samples images, and here the channels are always 1
  2. Check whether a given path exists
  3. Iterate against the .npy file, and save each image into the given path

I am not sure whether I am using the best practices to save an nd array into an image.

import numpy as npfrom scipy.misc import toimage, imsaveimport osimage_path = "raw"def ensure_directory_exist(image_path):    if not os.path.exists(image_path):        print("Allocating '{:}'",format(image_path))        os.mkdir(image_path)if __name__ == '__main__':    img_array = np.load('imgs_mask_test.npy')    ensure_directory_exist(image_path)    for i in range(img_array.shape[0]):       name = "img"+str(i)+".png"       imsave(os.path.join(image_path,name),img_array[i,0])
Jamal's user avatar
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
askedNov 29, 2016 at 20:19
user288609's user avatar
\$\endgroup\$

1 Answer1

2
\$\begingroup\$
  1. Instead of:

    ensure_directory_exist(image_path)

    use the built-inos.makedirs:

    os.makedirs(image_path, exist_ok=True)
  2. Iterate over the images themselves (rather than their indexes) and so avoid the lookupimg_array[i, 0] on each iteration:

    for i, img in enumerate(img_array[:, 0, :, :]):    name = "img{}.png".format(i)    imsave(os.path.join(image_path, name), img)
answeredJan 1, 2017 at 9:45
Gareth Rees's user avatar
\$\endgroup\$

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.