I have 32 npy files with the shape (32,160,256) and I want to convert them as png images with the same shape

I tried this and gave me error
input_folder = ‘/home/aya/mywork/training/mask1’
output_folder =‘/home/aya/mywork/training/mask’
os.makedirs(output_folder, exist_ok=True)

for file_name in os.listdir(input_folder):
if file_name.endswith(‘.npy’):
file_path = os.path.join(input_folder, file_name)
array = np.load(file_path)
array=array.squeeze()
plt.imshow(array)
plt.axis(‘off’)
output_file_path = os.path.splitext(file_name)[0]+‘.png’
output_file_path = os.path.join(output_folder, output_file_path,dpi=300)
plt.close()

the error :slight_smile:
TypeError: Invalid shape (32, 160, 256) for image data

Hi @Aya_Elfatyany, The image shape for color image will be (Img_height,Img_width, channels=3), (Img_height,Img_width, channels=1) for gray scale image. But in your shape you have 256 channels, which is not a suitable shape for an image. Thank you!

my image is as folllows : image(n_batch, Img_height, Img_width) how can solve this problem with respect to the batch size

Hi @Aya_Elfatyany, You can save the images from the numpy array using the below code

y_batch_pred=tf.random.normal((32,160,256))
image_array = np.squeeze(y_batch_pred)
for i in range(32):
  image=Image.fromarray((image_array[i].astype('uint8')))
  image.save(output_path[i])

Please refer to this gist for working code example. Thank You!