Home >Backend Development >Python Tutorial >Python method to read all images in a specified folder
The following is a Python method for reading all images in a specified folder. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
(1) Data preparation
Data set introduction:
The data set stores 1223 There are 756 negative samples (image names are 0.1~0.756) and 458 positive samples (image names are 1.1~1.458), among which: the label before "." is the sample label, and the label after "." is the sample Serial number
(2) Use python to read all images in the folder
''' Load the image files form the folder input: imgDir: the direction of the folder imgName:the name of the folder output: data:the data of the dataset label:the label of the datset ''' def load_Img(imgDir,imgFoldName): imgs = os.listdir(imgDir+imgFoldName) imgNum = len(imgs) data = np.empty((imgNum,1,12,12),dtype="float32") label = np.empty((imgNum,),dtype="uint8") for i in range (imgNum): img = Image.open(imgDir+imgFoldName+"/"+imgs[i]) arr = np.asarray(img,dtype="float32") data[i,:,:,:] = arr label[i] = int(imgs[i].split('.')[0]) return data,label
The data and label obtained here are both ndarray data
data: (1223,1,12,12)
##label:(1223,) Note: The nddary data type is a data type provided by numpy, that is, N-dimensional array, which makes up for the defect that array in python does not support multi-dimensionality(3) Calling method
craterDir = "./data/CraterImg/Adjust/" foldName = "East_CraterAdjust12" data, label = load_Img(craterDir,foldName)Related recommendations:
An example of how python reads a csv file and puts the file into a list
Python implements the method of generating a txt file with labels for the pictures in the file
The above is the detailed content of Python method to read all images in a specified folder. For more information, please follow other related articles on the PHP Chinese website!