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)