调试程序:

打印图片类型:

print(type(x_train))

读取图片:

1.opencv

import cv2

CV2读取图片:

import os
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
import cv2

def load_image(image_name,data_dir,image_extension= '.jpg'):
'''
cv2读取图片是以BGR的格式显示
'''
path = os.path.join(data_dir,image_name + image_extension)
image_cv2 = cv2.imread(path) #读取的直接是BGR

#cv2.imread返回np.array,使用cv2.imshow显示

return image_cv2
data_dir = 'C:/Users/Administrator/Desktop/python_learning/'
image_cv2 = load_image('000001',data_dir)

cv2.imwrite("hu2.jpg",img_array)
def readfile(path, label):
# label 是一個 boolean variable,代表需不需要回傳 y 值
image_dir = sorted(os.listdir(path))
x = np.zeros((len(image_dir), 128, 128, 3), dtype=np.uint8)
y = np.zeros((len(image_dir)), dtype=np.uint8)
for i, file in enumerate(image_dir):
img = cv2.imread(os.path.join(path, file))
x[i, :, :] = cv2.resize(img,(128, 128))
if label:
y[i] = int(file.split("_")[0])
if label:
return x, y
else:
return x

2.os获取图像标签

python文件读取、os文件读取

os常见操作

os.listdir( )函数读取文件夹下文件名并排序输出

os.path.join(path,filename)

文件模式选择:

r:(默认)
- 只能读,不能写
- 读取文件不存在,会报错
FileNotFoundError: [Errno 2] No such file or directory:

w:
- write only
- 文件不存在,不报错,并创建新的文件
- 文件存在,会清空文件内容并写入新的内容

a:
- write only
- 写:文件不存在,不报错,并创建新的文件
- 写:不会清空原文件的内容,会在文件末尾追加

a+:
- rw
- 文件不存在,不报错
- 不会清空文件内容,在末尾追加

r+:
- 读写
- 文件不存在,报错
- 默认情况下,从文件指针所在的位置开始写入

w+:
-rw
-文件不存在,不报错
-会清空文件内容

3.PIL读取图片:

#引入库
from PIL import Image
import numpy as np


# 读取图片
img = Image.open("hu.jpg")#此时img是一个对象,还不是矩阵

#转换大小
new_img = img.resize((width, height), Image.BILINEAR)
#resize(size,resample,box)
#resample是重新采样使用的方法,仍然有Image.BICUBIC,PIL.Image.LANCZOS,PIL.Image.BILINEAR,PIL.Image.NEAREST这四种采样方法,默认是PIL.Image.NEAREST


#转换成numpy数组
img_array = np.array(img)

#numpy数组转换成image
Image.fromarray(np.uint8(img))


#split()(颜色通道分离)
r,g,b = img.split()
r.show()
g.show()
b.show()

# 保存图片
img2 = Image.fromarray(img_array)#实现array到image的转换
img2.save("hu3.jpg")

显示图片:

plt.imshow()函数负责对图像进行处理,并显示其格式,但是不能显示。

其后跟着plt.show()才能显示出来。(Image类型)

文件读取:

csv文件读取:

1.csv库

​​参考文章​​

2. numpy库

两种方法:np.loadtxt()、np.genfromtxt()

  • 用np.loadtxt()读取

数据中如果有空格,最好不要选择这种方法,需要单独判断nan,选取pandas方法

python读取图片、文件os.listdir( )函数读取文件夹下文件名并排序输出_opencv

pandas读取会自动识别NAN,结果:

python读取图片、文件os.listdir( )函数读取文件夹下文件名并排序输出_大数据_02

 

否则会报错:ValueError: Wrong number of columns at line 2

import numpy as np
b= np.loadtxt("./path_file/file.csv",delimiter=',')

python读取图片、文件os.listdir( )函数读取文件夹下文件名并排序输出_python_03

使用示例

python读取图片、文件os.listdir( )函数读取文件夹下文件名并排序输出_深度学习_04

  • 用np.genfromtxt()读取
import numpy as np
t_us = np.genfromtxt("./path_file/file.csv", delimiter=",")

3.pandas库

import pandas as pd
csv_data = pd.read_csv("./path_file/file.csv", encoding = 'UTF-8')