You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

yolov5_flask.py 4.1 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Author : linjie
  4. # detection: 基于yolov5+flask 网页端实现
  5. import os
  6. import cv2
  7. from base_camera import BaseCamera
  8. from models.experimental import attempt_load
  9. import torch
  10. import torch.nn as nn
  11. import torchvision
  12. import numpy as np
  13. import argparse
  14. from utils.datasets import *
  15. from utils.utils import *
  16. class Camera(BaseCamera):
  17. video_source = 'people.mp4'
  18. def __init__(self):
  19. if os.environ.get('OPENCV_CAMERA_SOURCE'):
  20. Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
  21. super(Camera, self).__init__()
  22. @staticmethod
  23. def set_video_source(source):
  24. Camera.video_source = source
  25. @staticmethod
  26. def frames():
  27. out, weights, imgsz = \
  28. 'inference/output', 'weights/yolov5s.pt', 640
  29. source = 'people.mp4'
  30. device = torch_utils.select_device()
  31. if os.path.exists(out):
  32. shutil.rmtree(out) # delete output folder
  33. os.makedirs(out) # make new output folder
  34. # Load model
  35. model = attempt_load(weights, map_location=device) # load FP32 model
  36. model.to(device).eval()
  37. # Second-stage classifier
  38. classify = False
  39. if classify:
  40. modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize
  41. modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
  42. modelc.to(device).eval()
  43. # Half precision
  44. half = False and device.type != 'cpu'
  45. print('half = ' + str(half))
  46. if half:
  47. model.half()
  48. # Set Dataloader
  49. vid_path, vid_writer = None, None
  50. dataset = LoadImages(source, img_size=imgsz)
  51. # dataset = LoadStreams(source, img_size=imgsz)
  52. names = model.names if hasattr(model, 'names') else model.modules.names
  53. colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
  54. # Run inference
  55. t0 = time.time()
  56. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  57. _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
  58. for path, img, im0s, vid_cap in dataset:
  59. img = torch.from_numpy(img).to(device)
  60. img = img.half() if half else img.float() # uint8 to fp16/32
  61. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  62. if img.ndimension() == 3:
  63. img = img.unsqueeze(0)
  64. # Inference
  65. t1 = torch_utils.time_synchronized()
  66. pred = model(img, augment=False)[0]
  67. # Apply NMS
  68. pred = non_max_suppression(pred, 0.4, 0.5,
  69. fast=True, classes=None, agnostic=False)
  70. t2 = torch_utils.time_synchronized()
  71. # Apply Classifier
  72. if classify:
  73. pred = apply_classifier(pred, modelc, img, im0s)
  74. for i, det in enumerate(pred): # detections per image
  75. p, s, im0 = path, '', im0s
  76. save_path = str(Path(out) / Path(p).name)
  77. s += '%gx%g ' % img.shape[2:] # print string
  78. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  79. if det is not None and len(det):
  80. # Rescale boxes from img_size to im0 size
  81. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  82. # for c in det[:, -1].unique(): #probably error with torch 1.5
  83. for c in det[:, -1].detach().unique():
  84. n = (det[:, -1] == c).sum() # detections per class
  85. s += '%g %s, ' % (n, names[int(c)]) # add to string
  86. for *xyxy, conf, cls in det:
  87. label = '%s %.2f' % (names[int(cls)], conf)
  88. plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
  89. print('%sDone. (%.3fs)' % (s, t2 - t1))
  90. yield cv2.imencode('.jpg', im0)[1].tobytes()

随着人工智能和大数据的发展,任一方面对自动化工具有着一定的需求,在当下疫情防控期间,使用mindspore来实现yolo模型来进行目标检测及语义分割,对视频或图片都可以进行口罩佩戴检测和行人社交距离检测,来对公共场所的疫情防控来实行自动化管理。