Search code examples
pythonimagemultidimensional-arraysavetiff

How to save tiff images into a new npy file?


I would like to save some tiff images I have into a new npy file.

My data are saved in 5 different files (tiff format). I want to access to each one of them, convert them in narray and then save them in a new npy file (for deep learning classification).

import numpy as np 
from PIL import Image
import os

Data_dir = r"C:\Desktop\Université_2019_2020\CoursS2_Mosef\Stage\Data\Grand_Leez\shp\imagettes"
Categories = ["Bouleau_tiff", "Chene_tiff", "Erable_tiff", "Frene_tiff", "Peuplier_tiff"]

for categorie in Categories:
    path = os.path.join(Data_dir, categorie) #path for each species
    for img in os.listdir(path):
        path_img = os.path.join(path,img)
        im = Image.open(os.path.join(path_img)) #load an image file
        imarray = np.array(im) # convert it to a matrix
        imarray = np.delete(imarray, 3, axis=2)
        np.save(Data_dir, imarray)

Problem: It's only return me the last observation of my last category "Peuplier_tiff", also it's saved into the name imagette, I don't know why.

Last but not least, I have a doubt for my targets, how I can be sure that my categories are correctly assign to the corresponding arrays.

A lot of questions, thanks in advance for your help.

S.V


Solution

  • Thanks for your response. Its working with this code :

    import numpy as np
    from PIL import Image
    import os
    
    
    new_dir = "dta_npy"
    directory = r"C:\Desktop\Université_2019_2020\CoursS2_Mosef\Stage\Data\Grand_Leez\shp\imagettes"
    Data_dir = os.path.join(directory, new_dir)
    os.makedirs(Data_dir)
    print("Directory '%s' created" %Data_dir)
    
    Categories = ["Bouleau_tif","Chene_tif", "Erable_tif", "Frene_tif", "Peuplier_tif"]
    
    for categorie in Categories:
        path = os.path.join(directory,categorie) #path for each species
        for img in os.listdir(path):
            im = Image.open(os.path.join(path,img)) #load an image file
            imarray = np.array(im) # convert it to a matrix
            imarray = np.delete(imarray, 3, axis=2)
            unique_name=img
            unique_name = unique_name.split(".")
            unique_name = unique_name[0]
            np.save(Data_dir+"/"+unique_name, imarray)
            
    

    Now my objective is to format my data, for each of my class, in this way : (click on the link)

    format goal