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.

camera_test.py 10 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Author : linjie
  4. import os
  5. import cv2
  6. from base_camera import BaseCamera
  7. from models.experimental import attempt_load
  8. import torch.backends.cudnn as cudnn
  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. from utils.torch_utils import select_device, load_classifier, time_synchronized
  17. from flask import Flask,url_for
  18. from log import Logger
  19. from deep_sort_pytorch.deep_sort import DeepSort
  20. from deep_sort_pytorch.utils.parser import get_config
  21. class Camera(BaseCamera):
  22. #video_source = 'people.mp4'
  23. palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1)
  24. video_source = 'people.mp4'
  25. def __init__(self):
  26. if os.environ.get('OPENCV_CAMERA_SOURCE'):
  27. print('走了吗')
  28. Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
  29. super(Camera, self).__init__()
  30. print('走了')
  31. @staticmethod
  32. def set_video_source(source):
  33. Camera.video_source = source
  34. @staticmethod
  35. def bbox_rel(*xyxy):
  36. """" Calculates the relative bounding box from absolute pixel values. """
  37. bbox_left = min([xyxy[0].item(), xyxy[2].item()])
  38. bbox_top = min([xyxy[1].item(), xyxy[3].item()])
  39. bbox_w = abs(xyxy[0].item() - xyxy[2].item())
  40. bbox_h = abs(xyxy[1].item() - xyxy[3].item())
  41. x_c = (bbox_left + bbox_w / 2)
  42. y_c = (bbox_top + bbox_h / 2)
  43. w = bbox_w
  44. h = bbox_h
  45. return x_c, y_c, w, h
  46. @staticmethod
  47. def compute_color_for_labels(label):
  48. """
  49. Simple function that adds fixed color depending on the class
  50. """
  51. color = [int((p * (label ** 2 - label + 1)) % 255) for p in Camera.palette]
  52. return tuple(color)
  53. # @staticmethod
  54. # def people_appeal1():
  55. # a = 'people'
  56. # yield a
  57. @staticmethod
  58. def draw_boxes(img, bbox, cls_names, scores, identities=None, offset=(0,0)):
  59. for i, box in enumerate(bbox):
  60. x1, y1, x2, y2 = [int(i) for i in box]
  61. x1 += offset[0]
  62. x2 += offset[0]
  63. y1 += offset[1]
  64. y2 += offset[1]
  65. # box text and bar
  66. id = int(identities[i]) if identities is not None else 0
  67. color = Camera.compute_color_for_labels(id)
  68. label = '%d %s %d' % (id, cls_names[i], scores[i])
  69. label += '%'
  70. print("{0}号人物出现!========================================".format(id))
  71. t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]
  72. cv2.rectangle(img, (x1, y1), (x2, y2), color, 3)
  73. cv2.rectangle(
  74. img, (x1, y1), (x1 + t_size[0] + 3, y1 + t_size[1] + 4), color, -1)
  75. cv2.putText(img, label, (x1, y1 +
  76. t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 2, [255, 255, 255], 2)
  77. return img
  78. @staticmethod
  79. def frames():
  80. logger = Logger()
  81. print('初始化过了,。。。。。')
  82. camera = cv2.VideoCapture(Camera.video_source)
  83. if not camera.isOpened():
  84. raise RuntimeError('Could not start camera.')
  85. out, weights, imgsz = \
  86. '.inference/output', 'weights/yolov5s.pt', 640
  87. source = "people.mp4"
  88. # print(source)
  89. # print(type(source))
  90. #webcam = source.isnumeric()
  91. # print('看看webcam:{0}'.format(webcam))
  92. '''
  93. 初始化deepsort
  94. '''
  95. # initialize deepsort
  96. # cfg = get_config()
  97. # cfg.merge_from_file('deep_sort_pytorch/configs/deep_sort.yaml')
  98. # deepsort = DeepSort(cfg.DEEPSORT.REID_CKPT,
  99. # max_dist=cfg.DEEPSORT.MAX_DIST, min_confidence=cfg.DEEPSORT.MIN_CONFIDENCE,
  100. # nms_max_overlap=cfg.DEEPSORT.NMS_MAX_OVERLAP,
  101. # max_iou_distance=cfg.DEEPSORT.MAX_IOU_DISTANCE,
  102. # max_age=cfg.DEEPSORT.MAX_AGE, n_init=cfg.DEEPSORT.N_INIT, nn_budget=cfg.DEEPSORT.NN_BUDGET,
  103. # use_cuda=True)
  104. device = torch_utils.select_device()
  105. # print(weights)
  106. # print(os.getcwd())
  107. if os.path.exists(out):
  108. shutil.rmtree(out) # delete output folder
  109. os.makedirs(out) # make new output folder
  110. #shutil.rmtree(out)
  111. # Load model
  112. # google_utils.attempt_download(weights)
  113. # model = torch.load(weights, map_location=device)['model']
  114. model = attempt_load(weights, map_location=device) # load FP32 model
  115. model.to(device).eval()
  116. # Second-stage classifier
  117. classify = False
  118. if classify:
  119. modelc = load_classifier(name='resnet101', n=2) # initialize
  120. modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
  121. modelc.to(device).eval()
  122. # Half precision
  123. half = False and device.type != 'cpu'
  124. # print('half = ' + str(half))
  125. if half:
  126. model.half()
  127. # Set Dataloader
  128. vid_path, vid_writer = None, None
  129. # #if webcam:
  130. # view_img = True
  131. # cudnn.benchmark = True # set True to speed up constant image size inference
  132. # dataset = LoadStreams(source, img_size=imgsz)
  133. # else:
  134. # save_img = True
  135. # # # 如果检测视频的时候想显示出来,可以在这里加一行view_img = True
  136. # view_img = True
  137. # dataset = LoadImages(source, img_size=imgsz)
  138. # vid_path, vid_writer = None, None
  139. dataset = LoadImages(source, img_size=imgsz)
  140. #dataset = LoadStreams(source, img_size=imgsz)
  141. # print('看看dataset:{0}'.format(dataset))
  142. names = model.names if hasattr(model, 'names') else model.modules.names
  143. # print('----')
  144. # print(names)
  145. colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
  146. # Run inference
  147. t0 = time.time()
  148. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  149. _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
  150. for frame_idx, (path, img, im0s, vid_cap) in enumerate(dataset):
  151. img = torch.from_numpy(img).to(device)
  152. img = img.half() if half else img.float() # uint8 to fp16/32
  153. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  154. if img.ndimension() == 3:
  155. img = img.unsqueeze(0)
  156. # Inference
  157. t1 = torch_utils.time_synchronized()
  158. pred = model(img, augment=False)[0]
  159. # Apply NMS
  160. pred = non_max_suppression(pred, 0.4, 0.5,
  161. fast=True, classes=None, agnostic=False)
  162. t2 = torch_utils.time_synchronized()
  163. # Apply Classifier
  164. if classify:
  165. pred = apply_classifier(pred, modelc, img, im0s)
  166. people_coords = []
  167. for i, det in enumerate(pred): # detections per image
  168. #p, s, im0 = path, '', im0s
  169. p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
  170. #save_path = str(Path(out) / Path(p).name)
  171. s += '%gx%g ' % img.shape[2:] # print string
  172. #gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] #  normalization gain whwh
  173. if det is not None and len(det):
  174. # Rescale boxes from img_size to im0 size
  175. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  176. #for c in det[:, -1].unique(): #probably error with torch 1.5
  177. for c in det[:, -1].detach().unique():
  178. n = (det[:, -1] == c).sum() # detections per class
  179. s += '%g %s, ' % (n, names[int(c)]) # add to string
  180. # --- linjie
  181. # bbox_xywh = []
  182. # confs = []
  183. # clses = []
  184. # for *xyxy, conf, cls in det:
  185. # label = '%s %.2f' % (names[int(cls)], conf)
  186. # plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
  187. # Write results
  188. for *xyxy, conf, cls in reversed(det):
  189. # -- linjie deepsort
  190. # x_c, y_c, bbox_w, bbox_h = Camera.bbox_rel(*xyxy)
  191. # obj = [x_c, y_c, bbox_w, bbox_h]
  192. # bbox_xywh.append(obj)
  193. # confs.append([conf.item()])
  194. # clses.append([cls.item()])
  195. label = '%s %.2f' % (names[int(cls)], conf)
  196. print('看看这次打的标签:{0}'.format(label))
  197. plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
  198. # 判断标签是否为人 --linjie
  199. if label is not None:
  200. if (label.split())[0] == 'person':
  201. logger.info('当前进程:{0}.遇到了人'.format(os.getpid()))
  202. #print('标签是人')
  203. # distancing(people_coords, im0, dist_thres_lim=(200, 250))
  204. # people_coords.append(xyxy)
  205. plot_one_box(xyxy, im0, line_thickness=3)
  206. plot_dots_on_people(xyxy, im0)
  207. print('%sDone. (%.3fs)' % (s, t2 - t1))
  208. # Stream results
  209. # if view_img:
  210. # cv2.imshow(p, im0)
  211. # if cv2.waitKey(1) == ord('q'): # q to quit
  212. # raise StopIteration
  213. yield cv2.imencode('.jpg', im0)[1].tobytes()

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