1 # -*- coding: utf-8 -*-
2
3 import os
4 import sys
5 import numpy as np
6 import cv2
7
8 IMAGE_SIZE = 224
9
10
11 # 按照指定图像大小调整尺寸
12 def resize_image(image, height=IMAGE_SIZE, width=IMAGE_SIZE):
13 top, bottom, left, right = (0, 0, 0, 0)
14
15 # 获取图像尺寸
16 h, w, _ = image.shape
17
18 # 对于长宽不相等的图片,找到最长的一边
19 longest_edge = max(h, w)
20
21 # 计算短边需要增加多上像素宽度使其与长边等长
22 if h < longest_edge:
23 dh = longest_edge - h
24 top = dh // 2
25 bottom = dh - top
26 elif w < longest_edge:
27 dw = longest_edge - w
28 left = dw // 2
29 right = dw - left
30 else:
31 pass
32
33 # RGB颜色
34 BLACK = [0, 0, 0]
35
36 # 给图像增加边界,是图片长、宽等长,cv2.BORDER_CONSTANT指定边界颜色由value指定
37 constant = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)
38
39 # 调整图像大小并返回
40 return cv2.resize(constant, (height, width))
41
42
43 # 读取训练数据
44 images = []
45 labels = []
46
47
48 def read_path(path_name):
49 for dir_item in os.listdir(path_name):
50 # 从初始路径开始叠加,合并成可识别的操作路径
51 full_path = os.path.abspath(os.path.join(path_name, dir_item))
52
53 if os.path.isdir(full_path): # 如果是文件夹,继续递归调用
54 read_path(full_path)
55 else: # 文件
56 if dir_item.endswith('.jpg'):
57 image = cv2.imread(full_path)
58 image = resize_image(image, IMAGE_SIZE, IMAGE_SIZE)
59
60 # 放开这个代码,可以看到resize_image()函数的实际调用效果
61 # cv2.imwrite('1.jpg', image)
62
63 images.append(image)
64 labels.append(path_name)
65
66 return images, labels
67
68
69 # 从指定路径读取训练数据
70 def load_dataset(path_name):
71 images, labels = read_path(path_name)
72
73 # 将输入的所有图片转成四维数组,尺寸为(图片数量*IMAGE_SIZE*IMAGE_SIZE*3)
74 # 我和闺女两个人共1200张图片,IMAGE_SIZE为64,故对我来说尺寸为1200 * 64 * 64 * 3
75 # 图片为64 * 64像素,一个像素3个颜色值(RGB)
76 images = np.array(images)
77 print(images.shape)
78
79 # 标注数据,'me'文件夹下都是我的脸部图像,全部指定为0,另外一个文件夹下是闺女的,全部指定为1
80 labels = np.array([0 if label.endswith('me') else 1 for label in labels])
81
82 return images, labels
83
84 path = 'D:/pycode/facial-keypoints-master/test/'
85 if __name__ == '__main__':
86 img = cv2.imread(path+'000891.jpg')
87 image = resize_image(img)
88 cv2.imshow('img', image)
89 cv2.imwrite("D:\\1.jpg", image)
90 cv2.waitKey(0)
91 cv2.destroyAllWindows()
92
93 if len(sys.argv) != 2:
94 print("Usage:%s path_name\r\n" % path)
95 else:
96 images, labels = load_dataset(path)