HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python script to store nd array into images

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptarrayintostorepythonimages

Problem

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

  • Load .npy file (the .npy file is of shape (m_samples, channels, row, column), which corresponds to m_samples images, and here the channels are always 1



  • Check whether a given path exists



  • 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 np
from scipy.misc import toimage, imsave
import os
image_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])

Solution

-
Instead of:

ensure_directory_exist(image_path)


use the built-in os.makedirs:

os.makedirs(image_path, exist_ok=True)


-
Iterate over the images themselves (rather than their indexes) and so avoid the lookup img_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)

Code Snippets

ensure_directory_exist(image_path)
os.makedirs(image_path, exist_ok=True)
for i, img in enumerate(img_array[:, 0, :, :]):
    name = "img{}.png".format(i)
    imsave(os.path.join(image_path, name), img)

Context

StackExchange Code Review Q#148485, answer score: 2

Revisions (0)

No revisions yet.