在上一节中我们得到了训练数据和测试数据的图像,在本小节中,需要对该图片进行简单的处理,主要是将图片均调整为同样的大小,不够的地方填充黑色
一、总体结构
1.1 读取子目录下的所有数据集
images,labels = read_path(path_name,son_path_name)
read_path函数的实现在接下来介绍。其中主要包括读取数据,调整图片大小等功能。
1.2 将输入的所有图片转成四维数组
images = np.array(images)
images尺寸为 ( 图片数量 * IMAGE_SIZE * IMAGE_SIZE * 3 )
1.3 设置样本的标志 1为正样本 0为负样本
labels = np.array([0 if label==('traindata') else 1 for label in labels])
labels是一个一维数组 数组维度:1*图片数量 如果是traindata 则为0 如果是testdata 则为1
二、read_path函数实现
def read_path(path_name,son_path_name):
exit_code = file_exit(path_name,son_path_name) #判断该路径下是否有数据
if exit_code == 1: #如果有,则全路径是当前路径上一级+测试集文件夹名
full_path = path_name + '/' + son_path_name
for dir_item in os.listdir(full_path): #遍历所有的图片
if dir_item.endswith('.jpg'): #如果格式是图片,则进行大小处理
image = cv2.imread(full_path+'/'+dir_item)
image = resize_image(image,IMAGE_SIZE,IMAGE_SIZE)
images.append(image) #将图片加入到队列
labels.append(son_path_name) #将标签加入到队列
#print (labels)
return images,labels
主要功能 file_exit 读取图片数据以及resize_image
三、file_exit
#判断path_name文件夹下是否有file_name
def file_exit(path_name,son_path_name):#判断path_name文件夹下是否有file_name
lists = os.listdir(path_name)#该目录下的所有文件夹
for list in lists:
#遍历所有文件,如果存在与son_path_name同名的文件夹,返回1即找到测试集文件
if list == son_path_name:
print ('file exits')
return 1
return 0
四、resize_image函数
def resize_image(image ,height=IMAGE_SIZE,width=IMAGE_SIZE):
top,bottom,left,right = (0,0,0,0)
#获得图像尺寸
h,w,_ = image.shape
#找到最长的一边
longest_edge = max(h,w)
#计算需要补充的像素
if h<longest_edge:
dh = longest_edge - h
top = dh // 2
bottom = dh - top
elif w<longest_edge:
dw = longest_edge - w
left = dw // 2
right = dw - left
else:
pass
black = [0,0,0]
# 给图像增加边界,是图片长、宽等长,cv2.BORDER_CONSTANT指定边界颜色由value指定
constant = cv2.copyMakeBorder(image,top,bottom,left,right,
cv2.BORDER_CONSTANT,value = black)
#返回调整之后的图像
return cv2.resize(constant,(height,width))
经过调整之后的图片均变为64*64大小 格式统一 方便后续处理
源码下载地址:http://download.csdn.net/download/yunge812/10269872
=======================================================================
最近新开的公众号,文章正在一篇篇的更新,
公众号名称: 玩转电子世界
各位朋友有什么问题了可以直接在上面提问,我会一一进行解答的。
跟着阳光非宅男,一步步走进电子的世界。
关注之后回复 资料下载 关键词可以获得 免费海量的视频学习资料
免费海量的视频学习资料下载~~!
已共享的学习视频资料,共享资料正在不断更新中。
共享机器学习/tensorflow频学习资料:
=======================================================================