如下述代码,当采集了一些照片后想要停止人脸采集应该怎样做
import cv2
import dlib
import numpy as np
detector=dlib.get_frontal_face_detector()
cap=cv2.VideoCapture(0)
frame_count=0
face_count=0
font=cv2.FONT_HERSHEY_SIMPLEX
import keyboard
import sys
while True:
if keyboard.is_pressed('q'):
print('User pressed the "q" key, stopping image capture...')
sys.exit()
while True:
ret,frame=cap.read()
if (ret !=True):
print('没有捕获摄像头,数据采集结束或者检查摄像头是否正常工作!')
break
frame_count+=1
detected=detector(frame,1)
faces=[]
if len(detected)>0:
for i,d in enumerate(detected):
face_count+=1
x1,y1,x2,y2,w,h=d.left(),d.top(),d.right()+1,d.bottom()+1,d.width(),d.height()
face=frame[y1:y2+1,x1:x2+1,:]
if (frame_count % 4 !=0):
file_name="./dataset/train/one/"+str(frame_count)+"_one"+str(i)+".jpg"
else:
file_name="./dataset/valid/one/"+str(frame_count)+"_one"+str(i)+".jpg"
cv2.imwrite(file_name,face)
cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)
cv2.putText(frame,f"already get:{frame_count},faces",\
(80,80),font,1.2,(255,0,0),3)
cv2.imshow("Face Detector",frame)
if cv2.waitKey(1) & 0xFF ==27:
break
print('已经完成了{0}帧检测,共保存了{1}幅脸部图像'.format(frame_count,face_count))
cap.release()
cv2.destoryAllWindows()
x_train.shape, x_test.shape
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
x_train.shape, x_test.shape
x_train = tf.cast(x_train, tf.float32)/255
x_test = tf.cast(x_test, tf.float32)/255
noise_factor = 0.5
x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)
x_train_noisy = np.clip(x_train_noisy, 0., 1.)
x_test_noisy = np.clip(x_test_noisy, 0., 1.)
n = 10
plt.figure(figsize=(10, 2))
for i in range(1, n):
# 展示原始图像
ax = plt.subplot(1, n, i)
plt.imshow(x_train_noisy[i].reshape(28, 28))
plt.show()
input = tf.keras.layers.Input(shape=(28, 28, 1))
# Encoder
x = tf.keras.layers.Conv2D(16, (3, 3), activation='relu', padding='same')(input)
x = tf.keras.layers.MaxPool2D((2, 2), padding='same')(x) # 14*14*16
x = tf.keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x = tf.keras.layers.MaxPool2D((2, 2), padding='same')(x) # 7*7*32
# Decoder
x = tf.keras.layers.Conv2DTranspose(16, (3, 3), strides=2,
activation='relu', padding='same')(x) # 14*14*16
output = tf.keras.layers.Conv2DTranspose(1, (3, 3), strides=2,
activation='sigmoid', padding='same')(x) # 28*28*1
model = tf.keras.Model(inputs=input, outputs=output)
model.compile(optimizer='adam', loss='mse')
model.fit(x_train_noisy, x_train,
nb_epoch=50,
batch_size=256,
validation_data=(x_test_noisy, x_test))
pre_test = model.predict(x_test_noisy)
plt.figure(figsize=(20, 4))
for i in range(1, n):
# 展示原始图像
ax = plt.subplot(2, n, i)
plt.imshow(x_test_noisy[i].reshape(28, 28))
# 展示自编码器重构后的图像
ax = plt.subplot(2, n, i + n)
plt.imshow(pre_test[i].reshape(28, 28))
plt.show()
model.layers