Search code examples
pythonimage-preprocessingmedical-imaging

How to store .npy file as a folder containing images


I am using the GRAD-CAM module that converts the images in a folder first to an array X and then after performing operations to a .npy file. But I would like to have this array back in image format and stored in a folder. How can I proceed further?

dir_path = '/content/drive/MyDrive/Datasets/ircad/raw/Original_sliced_train/'
files = os.listdir(dir_path)
N = len(files)

X = np.empty((N, H, W, 3))
for i, file in enumerate(files):
     x = image.load_img(dir_path + file, target_size=(H, W))
     X[i] = image.img_to_array(x)
X = preprocess_input(X)

top = np.argmax(model.predict(X), 1)

gradcam = np.empty((X.shape[:-1]))
batch_size = 32
for i in range((N + batch_size - 1) // batch_size):
    start = i * batch_size
    end = min((i+1) * batch_size, N)
    gradcam[start:end] = grad_cam_batch(model, X[start:end], top[start:end], 'block5_conv3')

gradcam.tofile('gradcam.npy')

Solution

  • If I understood right you want to save the output of gradcam as an image instead of .npy, right? In that case you can just replace your last line of code with something like cv2.imwrite("gradcam.png",gradcam), but you have to import cv2.