Introduction:
As no see, such as three years, hello! Hello, I’m Muzi.
Look down: | | | | | |
This picture is just to tell everyone that although the epidemic is under control, everyone still remembers to wear masks and take personal protective measures when going out!!
Actively vaccinate against COVID-19. Vaccination against COVID-19 is also one of the most effective measures to prevent Novel coronavirus infection.
Everybody blows! Xiaobian must be hit but at present is only 2 drops. Be to hit when still a bit plunge shoulder, be the 2nd needle a bit ache ~
When you go to work and go out, do you need to wear masks during the epidemic? People in the community, especially doctors and nurses in hospitals, always wear masks on their hands. The same is true when entering hospitals, they cannot go in without masks.
Today xiaobian with you to do a face detection wearing masks small procedures!!
By the way, the benefits of wearing a mask:
The mask is on. Is that right?
After you have identified the front, back, top and bottom of the mask, wash your hands and make sure the mask is correct, then hang the strings from both ends over your ears. Finally, after wearing the mask, press the metal strips on both sides of the nose bridge with both hands so that the upper part of the mask is pressed against the nose bridge, and then stretch the mask downward so that there are no wrinkles, preferably covering the nose and mouth.
The body of the
(1) Mask data set created first.
(2) Secondly, adjust the size of the focus area to A 100×100 and pass it to the pre-trained CNN, which will provide the probability as the output.
Step 1: Data pretreatment:
The data set used consists of images of different colors, sizes and orientations. Therefore, you need to convert all images to grayscale because you need to ensure that color should not be a key point in the detection mask. After that, 100×100 needs to make all images the same size before it can be applied to the neural network.
import cv2,os import numpy as np from keras.utils import np_utils data_path='dataset' categories=os.listdir(data_path) labels=[i for i in range(len(categories))] label_dict=dict(zip(categories,labels)) data=[] target=[] for category in categories: folder_path=os.path.join(data_path,category) img_names=os.listdir(folder_path) for img_name in img_names: img_path=os.path.join(folder_path,img_name) img=cv2.imread(img_path) try: gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) resized=cv2.resize(gray,(100, 100))dataset data.append(resized) target.append(label_dict[category]) except Exception as e: Print (' Exception: 'e) data = np, array (data) / 255.0 data = np. Reshape (data, (data. The shape [0], 100, 100, 1)) target = np array (target) new_target = np_utils. To_categorical (target) np. Save (' data 'data) np.save('target',new_target)Copy the code
Step 2: Train CNN
This consists of two convolution layers. First, the data set must be loaded from the data preprocessing. Then, the convolution architecture must be configured. Provide model.Add (Dropout(0.5)) features to get rid of overfitting. Since there are two categories (masked and unmasked), you can use binary_crossentropy. When you start training with model checkpoints for 20 eras.
import numpy as np from keras.models import Sequential from keras.layers import Dense,Activation,Flatten,Dropout from keras.layers import Conv2D,MaxPooling2D from keras.callbacks import ModelCheckpoint from sklearn.model_selection import train_test_split data=np.load('data.npy') target=np.load('target.npy') model=Sequential() Model. The add (Conv2D (100, (3, 3), input_shape = data. The shape [1])) model. The add (Activation (' relu)) Model. The add (MaxPooling2D (pool_size = (2, 2))) model. The add (Conv2D (100), (3, 3))) model. The add (Activation (' relu)) Model. The add (MaxPooling2D (pool_size = (2, 2))) model. The add (Flatten ()) model. The add (Dropout (0.5)) model.add(Dense(50,activation='relu')) model.add(Dense(2,activation='softmax')) model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) Train_data, test_data, train_target test_target = train_test_split (data, target, test_size = 0.1) : = ModelCheckpoint ( 'model-{epoch:03d}.model', monitor='val_loss', verbose=0, save_best_only=True, mode='auto') history=model.fit( train_data, train_target, epochs=20, callbacks=[checkpoint], Validation_split = 0.2) print (model. The evaluate (test_data, test_target))Copy the code
Step 3: Detect faces without masks:
from keras.models import load_model import cv2 import numpy as np model = load_model('model-017.model') face_clsfr=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') source=cv2.VideoCapture(0) Labels_dict = {0: 'with_mask, 1:' without_mask} color_dict = {0 (0255, 0), 1 (0,0,255)} while (True) : Ret, img = source. The read () gray. = cv2 cvtColor (img, cv2 COLOR_BGR2GRAY) faces. = face_clsfr detectMultiScale (gray, 1.3, 5) x,y,w,h in faces: Face_img = gray [y, y + w, x, x + w] resized = cv2. Resize (face_img, (100100)) normalized = 255.0 / resized Reshaped = np. Reshape (normalized, (1100100, 1)) result = model, predict (reshaped) label = np. Argmax (result, axis = 1) [0] cv2.rectangle(img,(x,y),(x+w,y+h),color_dict[label],2) cv2.rectangle(img,(x,y-40),(x+w,y),color_dict[label],-1) cv2.putText( img, labels_dict[label], (x, y-10), Cv2. FONT_HERSHEY_SIMPLEX, 0.8 (255255255), 2) cv2. Imshow (' LIVE 'img) key = cv2. WaitKey (1) if (key = = 27) : break cv2.destroyAllWindows() source.release()Copy the code
“With_mask” in green means wearing a mask, while “without_mask” in red means not wearing a mask.
conclusion
A mask does not guarantee protection from infection, but it does reduce the chance that the general public will not be infected. Wearing a mask is not only to protect yourself, but also to protect others, as well as your family.
Don’t just think about what masks mean to you, but what they mean to the public. Therefore, the meaning of wearing a mask in the COVID-19 pandemic: not everyone for me, but one for everyone, everyone remember to take good protection, vaccination is finished
“Mask area, everyone loves ~” source base: #959755565# Remember three lian oh ~