第一关 :读入一幅图像
import cv2
import numpy as np
def Read(path):
#读取path所指定的图片,转换并返回一个一维向量
# 请在此添加实现代码 #
# ********** Begin *********#
mat = np.zeros(128*128) # 每个图像对应一行
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
rows, columns = img.shape
vec = img.reshape( rows*columns)
mat = vec
return mat
# ********** End **********#
第二关:读入一个目录下所有图像
import cv2
import os
import numpy as np
def ReadAll(dir):
#读取指定目录下的所有图像,并转换成一个矩阵
# 请在此添加实现代码 #
# ********** Begin *********#
# 读取指定目录下的所有图像,并转换成一个矩阵
imgfiles = os.listdir(dir)
# 初始化图像数据矩阵 (N行,128*128列)
N = len(imgfiles)
mat = np.zeros((N,128*128)) # 每个图像对应一行
for i in range(N):
# 图像不在当前目录,因此需要加上目录前缀
imgpath = dir +"/" + imgfiles[i]
img = cv2.imread(imgpath, cv2.IMREAD_GRAYSCALE)
rows, columns = img.shape
vec = img.reshape( rows*columns)
mat[i] = vec
return mat
# ********** End **********#