def predict(img): """ 加载模型和模型预测 :param img: cv2.imread 图像 :return: 预测的图片中的总人数、其中佩戴口罩的人数 """ # -------------------------- 实现模型预测部分的代码 --------------------------- # 将 cv2.imread 图像转化为 PIL.Image 图像,用来兼容测试输入的 cv2 读取的图像(勿删!!!) # cv2.imread 读取图像的类型是 numpy.ndarray # PIL.Image.open 读取图像的类型是 PIL.JpegImagePlugin.JpegImageFile if isinstance(img, np.ndarray): # 转化为 PIL.JpegImagePlugin.JpegImageFile 类型 img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) recognize = Recognition(model_path) img, all_num, mask_num = recognize.mask_recognize(img) # ------------------------------------------------------------------------- return all_num, mask_num
plot_image(img) for index, (x, labels) in enumerate(train_data_loader): print(index, "\nfeature:", x[0], "\nlabels:", labels) # 打印每个batch中第一张图片的feature,和所有label show_tensor_img(x) break # 训练集一共有20个batch pnet_path = "./torch_py/MTCNN/weights/pnet.npy" rnet_path = "./torch_py/MTCNN/weights/rnet.npy" onet_path = "./torch_py/MTCNN/weights/onet.npy" torch.set_num_threads(1) # 读取测试图片 img = Image.open("test.jpg") # 加载模型进行识别口罩并绘制方框 recognize = Recognition() draw = recognize.face_recognize(img) plot_image(draw) # 加载 MobileNet 的预训练模型权 device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device( "cpu") # 选择运算设备 train_data_loader, valid_data_loader = processing_data(data_path=data_path, height=160, width=160, batch_size=32) modify_x, modify_y = torch.ones((32, 3, 160, 160)), torch.ones((32)) epochs = 1000 model = MobileNetV1(classes=2).to(device) optimizer = optim.Adam(model.parameters(), lr=1e-3) # 优化器:lr即学习率0.001 print('加载完成...')
optimizer.step() # 梯度更新 if loss < best_loss: # 选择最小损失 best_model_weights = copy.deepcopy(model.state_dict()) best_loss = loss #loss_list.append(loss) # 存储损失函数 print('{{"metric": "loss", "value": {}}}'.format(loss)) # 迭代一轮计算accuracy # 模型路径 model_path = './results/temp.pth' # 临时保存net torch.save(model.state_dict(), model_path) # 加载网络 temp_net = Recognition(model_path) correct = 0 total = 0 best_val_loss = 1e9 with torch.no_grad():# 执行的固定操作 for index, (x, labels) in enumerate(valid_data_loader): print("index:",index) temp_correct = 0 size = labels.size(0) print("size:",size) total += size # 可视化valid loss x = x.to(device) y = labels.to(device) pred_y = model(x)
resolution_op = 256 first_dir = os.listdir(image_folder) num = 0 for img in first_dir: # 二级目录绝对路径 if img.split(".")[-1] == 'jpg' or img.split(".")[-1] == 'JPG': path_image = image_folder + '/' + str(img) #if int((img.split(".")[0]).split("_")[-2]) == 1: image = Image.open(path_image) #image = cv2.imread(path_image) num = num + 1 print(num, str(img)) recognize = Recognition() #draw = recognize.face_recognize(img) #plot_image(draw) if not recognize.crop_faces(image): #face_img = image print("Failed!!") continue #plot_image(image) else: face_img = recognize.crop_faces(image)[0] #plot_image(face_img) save_path = save_folder + '/' + str(img) face_img.save(save_path) #cv2.imwrite(save_path, face_img)
import torch import cv2 from PIL import Image import matplotlib.pyplot as plt from torch_py.Utils import plot_image from torch_py.MTCNN.detector import FaceDetector from torch_py.MobileNetV1 import MobileNetV1 from torch_py.FaceRec import Recognition pnet_path = "./torch_py/MTCNN/weights/pnet.npy" rnet_path = "./torch_py/MTCNN/weights/rnet.npy" onet_path = "./torch_py/MTCNN/weights/onet.npy" img = Image.open("image/test.jpg") detector = FaceDetector() recognize = Recognition(model_path='./results/modelV1.pkl') draw, all_num, mask_nums = recognize.mask_recognize(img) print("总人数:", all_num, "戴口罩数", mask_nums) plt.title("total: %d, mask count: %d" % (all_num, mask_nums)) plt.imshow(draw) plt.show()