乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      口罩檢測識別率驚人,這個Python項目開源了

       板橋胡同37號 2020-03-08



      首先感謝 AIZOOTech 的開源項目 —— FaceMaskDetection??,以下為該項目的 GitHub 地址:
      https://github.com/AIZOOTech/FaceMaskDetection

      測試環(huán)境

      我們采用:
      • Windows 系統(tǒng);

      • 軟件:PyCharm;

      • 使用模型:TensorFlow。

      先看一下效果:
      檢測出帥氣的胡歌沒有帶口罩。紅色框框是圈出人臉部分,上方的字體:NoMask ,準確率 1 (即有 100% 把握認為沒帶口罩)。
      如果在多人的情況下,能檢測出來嗎?如下圖所示。
      不錯不錯,這個模型能同時檢測多人的,并且準確高。
      有人帶口罩,有人沒帶口罩,能檢測出來嗎?
      哇,這個模型很棒。檢測出帶口罩大叔,和兩個沒帶口罩的小伙子。
      大家可以先在網(wǎng)頁體驗一下:
      https:///face-mask-detection.html
      接下來,我們具體分析一下這個項目:
      • 支持 5 大主流深度學習框架(PyTorch、TensorFlow、MXNet、Keras 和 Caffe),已經(jīng)寫好接口了;可以根據(jù)自身的環(huán)境選擇合適的框架,比如:TensorFlow;所有模型都在 models 文件夾下。

      • 公開了近 8000 張的人臉口罩數(shù)據(jù)和模型,數(shù)據(jù)集來自于 WIDER Face 和 MAFA 數(shù)據(jù)集, 重新修改了標注并進行了校驗(主要是 MAFA 和 WIDER Face 的人臉位置定義不一樣,所以進行了修改標注)并將其開源出來。


      模型結(jié)構

      在本項目中使用了 SSD 類型的架構,為了讓模型可以實時的跑在瀏覽器以及終端設備上,將模型設計的非常小,只有 101.5 萬個參數(shù)。模型結(jié)構在本文附錄部分。
      本模型輸入大小為 260x260,主干網(wǎng)絡只有 8 個卷積層,加上定位和分類層,一共只有 24 層(每層的通道數(shù)目基本都是 32\64\128),所以模型特別小,只有 101.5 萬參數(shù)。模型對于普通人臉基本都能檢測出來,但是對于小人臉,檢測效果肯定不如大模型。
      網(wǎng)頁使用了 Tensorflow.js 庫,所以模型是完全運行在瀏覽器里面的。運行速度的快慢,取決于電腦配置的高低。
      模型在五個卷積層上接出來了定位分類層,其大小和 anchor 設置信息如下表。

      工程包目錄結(jié)構分析

      GitHub 工程包下載:
      https://github.com/AIZOOTech/FaceMaskDetection
      下載完 FaceMaskDetection 壓縮包后,解壓后如下圖:

      如何運行程序?

      以 TensorFlow 模型為例子,代碼中 TensorFlow 版本應該是 1.x;
      如果是 TensorFlow 版本是 2.x 的朋友,對應函數(shù)修改為 tf.compat.v1.xxxx,使函數(shù)與 1.x 版本兼容。
      如果想運行圖片:

      python tenforflow_infer.py  --img-path /path/to/your/img


      比如,img 目錄中作者放了一些圖片的,選擇 demo2.jpg。

      python tenforflow_infer.py  --img-path  img/demo2.jpg


      運行結(jié)果:
      如果想運行運行視頻:

      python tenforflow_infer.py --img-mode 0 --video-path /path/to/video


      /path/to/video 為視頻所在的路徑+視頻名。
      如果想實時使用攝像頭檢測:

      python tenforflow_infer.py --img-mode 0 --video-path 0


      這里的 0 ,代表在電腦中設備號;0 默認為電腦自帶的攝像頭。
      如果想使用外接攝像頭,可以改為 1 (比如外接上一個 USB 攝像頭)。
      這里看一下 tenforflow_infer.py 代碼:

      # -*- coding:utf-8 -*-
      import cv2
      import time
      import argparse

      import numpy as np
      from PIL import Image
      from keras.models import model_from_json
      from utils.anchor_generator import generate_anchors
      from utils.anchor_decode import decode_bbox
      from utils.nms import single_class_non_max_suppression
      from load_model.tensorflow_loader import load_tf_model, tf_inference


      #sess, graph = load_tf_model('FaceMaskDetection-master\models\face_mask_detection.pb')
      sess, graph = load_tf_model('models\face_mask_detection.pb')
      # anchor configuration
      feature_map_sizes = [[3333], [1717], [99], [55], [33]]
      anchor_sizes = [[0.040.056], [0.080.11], [0.160.22], [0.320.45], [0.640.72]]
      anchor_ratios = [[10.620.42]] * 5

      # generate anchors
      anchors = generate_anchors(feature_map_sizes, anchor_sizes, anchor_ratios)

      #用于推斷,批大小為1,模型輸出形狀為[1,N,4],因此將錨點的dim擴展為[1,anchor_num,4]
      anchors_exp = np.expand_dims(anchors, axis=0)
      id2class = {0'Mask'1'NoMask'}


      def inference(image, conf_thresh=0.5, iou_thresh=0.4, target_shape=(160160), draw_result=True, show_result=True):
          '''  檢測推理的主要功能
         # :param image:3D numpy圖片數(shù)組
          #  :param conf_thresh:分類概率的最小閾值。
         #  :param iou_thresh:網(wǎng)管的IOU門限
         #  :param target_shape:模型輸入大小。
         #  :param draw_result:是否將邊框拖入圖像。
         #  :param show_result:是否顯示圖像。
          '''

          # image = np.copy(image)
          output_info = []
          height, width, _ = image.shape
          image_resized = cv2.resize(image, target_shape)
          image_np = image_resized / 255.0  # 歸一化到0~1
          image_exp = np.expand_dims(image_np, axis=0)
          y_bboxes_output, y_cls_output = tf_inference(sess, graph, image_exp)

          # remove the batch dimension, for batch is always 1 for inference.
          y_bboxes = decode_bbox(anchors_exp, y_bboxes_output)[0]
          y_cls = y_cls_output[0]
          # 為了加快速度,請執(zhí)行單類NMS,而不是多類NMS。
          bbox_max_scores = np.max(y_cls, axis=1)
          bbox_max_score_classes = np.argmax(y_cls, axis=1)

          # keep_idx是nms之后的活動邊界框。
          keep_idxs = single_class_non_max_suppression(y_bboxes, bbox_max_scores, conf_thresh=conf_thresh,iou_thresh=iou_thresh)
          for idx in keep_idxs:
              conf = float(bbox_max_scores[idx])
              class_id = bbox_max_score_classes[idx]
              bbox = y_bboxes[idx]
              # 裁剪坐標,避免該值超出圖像邊界。
              xmin = max(0, int(bbox[0] * width))
              ymin = max(0, int(bbox[1] * height))
              xmax = min(int(bbox[2] * width), width)
              ymax = min(int(bbox[3] * height), height)

              if draw_result:
                  if class_id == 0:
                      color = (02550)
                  else:
                      color = (25500)
                  cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)
                  cv2.putText(image, '%s: %.2f' % (id2class[class_id], conf), (xmin + 2, ymin - 2),
                              cv2.FONT_HERSHEY_SIMPLEX, 1, color)
              output_info.append([class_id, conf, xmin, ymin, xmax, ymax])

          if show_result:
              Image.fromarray(image).show()
          return output_info


      def run_on_video(video_path, output_video_name, conf_thresh):
          cap = cv2.VideoCapture(video_path)
          height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
          width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
          fps = cap.get(cv2.CAP_PROP_FPS)
          fourcc = cv2.VideoWriter_fourcc(*'XVID')
          #writer = cv2.VideoWriter(output_video_name, fourcc, int(fps), (int(width), int(height)))
          total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
          if not cap.isOpened():
              raise ValueError('Video open failed.')
              return
          status = True
          idx = 0
          while status:
              start_stamp = time.time()
              status, img_raw = cap.read()
              img_raw = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
              read_frame_stamp = time.time()
              if (status):
                  inference(img_raw,
                            conf_thresh,
                            iou_thresh=0.5,
                            target_shape=(260260),
                            draw_result=True,
                            show_result=False)
                  cv2.imshow('image', img_raw[:, :, ::-1])
                  cv2.waitKey(1)
                  inference_stamp = time.time()
                  # writer.write(img_raw)
                  write_frame_stamp = time.time()
                  idx += 1
                  print('%d of %d' % (idx, total_frames))
                  print('read_frame:%f, infer time:%f, write time:%f' % (read_frame_stamp - start_stamp,
                                                                         inference_stamp - read_frame_stamp,
                                                                         write_frame_stamp - inference_stamp))
          # writer.release()


      if __name__ == '__main__':
          parser = argparse.ArgumentParser(description='Face Mask Detection')
          parser.add_argument('--img-mode', type=int, default=0, help='set 1 to run on image, 0 to run on video.')  #這里設置為1:檢測圖片;還是設置為0:視頻文件(實時圖像數(shù)據(jù))檢測
          parser.add_argument('--img-path', type=str, help='path to your image.')
          parser.add_argument('--video-path', type=str, default='0', help='path to your video, `0` means to use camera.')
          # parser.add_argument('--hdf5', type=str, help='keras hdf5 file')
          args = parser.parse_args()
          if args.img_mode:
              imgPath = args.img_path
              #img = cv2.imread('imgPath')
              img = cv2.imread(imgPath)
              img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
              inference(img, show_result=True, target_shape=(260260))
          else:
              video_path = args.video_path
              if args.video_path == '0':
                  video_path = 0
              run_on_video(video_path, '', conf_thresh=0.5)


      測試集 PR 曲線

      因為 WIDER face 是一個任務比較復雜的數(shù)據(jù)集,模型又設計的非常小,所以對于人臉的 PR 曲線并不是那么性感。這點可以通過設計大模型來提升對于小人臉的檢測效果。
      再次感謝 AIZOOTech 的開源項目 —— FaceMaskDetection。

      【end】


      原力計劃


      《原力計劃【第二季】- 學習力挑戰(zhàn)》正式開始!即日起至 3月21日,千萬流量支持原創(chuàng)作者!更有專屬【勛章】等你來挑戰(zhàn)

        本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多