Browse Source

gengxin

master
bai 3 years ago
parent
commit
fe0844c206
35 changed files with 171 additions and 1 deletions
  1. BIN
      inference/images/02720.jpg
  2. BIN
      inference/images/QQ图片20220212170445.jpg
  3. BIN
      inference/images/cat.jpg
  4. BIN
      inference/images/fa8cf1a163ef2cc5c7ac5c2e01f2da4.jpg
  5. BIN
      inference/images/horses.jpg
  6. +0
    -0
      inference/images/mask.jpeg
  7. BIN
      inference/images/zidane.jpg
  8. BIN
      inference/output/0062.jpg
  9. BIN
      inference/output/02040.jpg
  10. BIN
      inference/output/02720.jpg
  11. BIN
      inference/output/03580.jpg
  12. BIN
      inference/output/bus.jpg
  13. BIN
      inference/output/children.jpg
  14. BIN
      inference/output/mask.jpeg
  15. BIN
      inference/output/zidane.jpg
  16. BIN
      models/__pycache__/__init__.cpython-38.pyc
  17. BIN
      runs/detect/exp/cat.jpg
  18. BIN
      runs/detect/exp/fa8cf1a163ef2cc5c7ac5c2e01f2da4.jpg
  19. BIN
      runs/detect/exp/horses.jpg
  20. +0
    -0
      runs/exp0_results/events.out.tfevents.1597502075.28b44c60beac.274.0
  21. +0
    -0
      runs/exp0_results/hyp.yaml
  22. +0
    -0
      runs/exp0_results/labels.png
  23. +0
    -0
      runs/exp0_results/opt.yaml
  24. +0
    -0
      runs/exp0_results/results.png
  25. +0
    -0
      runs/exp0_results/results.txt
  26. +0
    -0
      runs/exp0_results/test_batch0_gt.jpg
  27. +0
    -0
      runs/exp0_results/test_batch0_pred.jpg
  28. +0
    -0
      runs/exp0_results/train_batch0.jpg
  29. +0
    -0
      runs/exp0_results/train_batch1.jpg
  30. +0
    -0
      runs/exp0_results/train_batch2.jpg
  31. +0
    -0
      runs/exp0_results/weights/best_yolov5s_results.pt
  32. +0
    -0
      runs/exp0_results/weights/last_yolov5s_results.pt
  33. BIN
      utils/__pycache__/__init__.cpython-38.pyc
  34. +170
    -0
      yolo_detect_distince.py
  35. +1
    -1
      yolo_detect_mask.py

BIN
inference/images/02720.jpg View File

Before After
Width: 960  |  Height: 540  |  Size: 130 kB

BIN
inference/images/QQ图片20220212170445.jpg View File

Before After
Width: 640  |  Height: 640  |  Size: 30 kB

BIN
inference/images/cat.jpg View File

Before After
Width: 500  |  Height: 324  |  Size: 88 kB

BIN
inference/images/fa8cf1a163ef2cc5c7ac5c2e01f2da4.jpg View File

Before After
Width: 4608  |  Height: 3456  |  Size: 4.2 MB

BIN
inference/images/horses.jpg View File

Before After
Width: 773  |  Height: 512  |  Size: 134 kB

inference/images/ffdad1f195b64d50b3bf092353613878.jpeg → inference/images/mask.jpeg View File


BIN
inference/images/zidane.jpg View File

Before After
Width: 1280  |  Height: 720  |  Size: 169 kB

BIN
inference/output/0062.jpg View File

Before After
Width: 960  |  Height: 540  |  Size: 150 kB Width: 960  |  Height: 540  |  Size: 148 kB

BIN
inference/output/02040.jpg View File

Before After
Width: 1024  |  Height: 820  |  Size: 158 kB

BIN
inference/output/02720.jpg View File

Before After
Width: 960  |  Height: 540  |  Size: 179 kB

BIN
inference/output/03580.jpg View File

Before After
Width: 1024  |  Height: 1155  |  Size: 198 kB

BIN
inference/output/bus.jpg View File

Before After
Width: 810  |  Height: 1080  |  Size: 481 kB Width: 810  |  Height: 1080  |  Size: 478 kB

BIN
inference/output/children.jpg View File

Before After
Width: 4608  |  Height: 3456  |  Size: 4.4 MB Width: 4608  |  Height: 3456  |  Size: 4.3 MB

BIN
inference/output/mask.jpeg View File

Before After
Width: 700  |  Height: 467  |  Size: 54 kB

BIN
inference/output/zidane.jpg View File

Before After
Width: 1280  |  Height: 720  |  Size: 234 kB

BIN
models/__pycache__/__init__.cpython-38.pyc View File


BIN
runs/detect/exp/cat.jpg View File

Before After
Width: 500  |  Height: 324  |  Size: 94 kB

BIN
runs/detect/exp/fa8cf1a163ef2cc5c7ac5c2e01f2da4.jpg View File

Before After
Width: 4608  |  Height: 3456  |  Size: 4.4 MB

BIN
runs/detect/exp/horses.jpg View File

Before After
Width: 773  |  Height: 512  |  Size: 154 kB

runs/exp0_yolov5s_results/events.out.tfevents.1597502075.28b44c60beac.274.0 → runs/exp0_results/events.out.tfevents.1597502075.28b44c60beac.274.0 View File


runs/exp0_yolov5s_results/hyp.yaml → runs/exp0_results/hyp.yaml View File


runs/exp0_yolov5s_results/labels.png → runs/exp0_results/labels.png View File


runs/exp0_yolov5s_results/opt.yaml → runs/exp0_results/opt.yaml View File


runs/exp0_yolov5s_results/results.png → runs/exp0_results/results.png View File


runs/exp0_yolov5s_results/results.txt → runs/exp0_results/results.txt View File


runs/exp0_yolov5s_results/test_batch0_gt.jpg → runs/exp0_results/test_batch0_gt.jpg View File


runs/exp0_yolov5s_results/test_batch0_pred.jpg → runs/exp0_results/test_batch0_pred.jpg View File


runs/exp0_yolov5s_results/train_batch0.jpg → runs/exp0_results/train_batch0.jpg View File


runs/exp0_yolov5s_results/train_batch1.jpg → runs/exp0_results/train_batch1.jpg View File


runs/exp0_yolov5s_results/train_batch2.jpg → runs/exp0_results/train_batch2.jpg View File


runs/exp0_yolov5s_results/weights/best_yolov5s_results.pt → runs/exp0_results/weights/best_yolov5s_results.pt View File


runs/exp0_yolov5s_results/weights/last_yolov5s_results.pt → runs/exp0_results/weights/last_yolov5s_results.pt View File


BIN
utils/__pycache__/__init__.cpython-38.pyc View File


+ 170
- 0
yolo_detect_distince.py View File

@@ -0,0 +1,170 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : linjie
# detection: 基于yolov5社交距离
import argparse

from utils.datasets import *
from utils.utils import *


def detect(save_img=False):
out, source, weights, view_img, save_txt, imgsz = \
opt.output, opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt')

# Initialize
device = torch_utils.select_device(opt.device)
if os.path.exists(out):
shutil.rmtree(out) # delete output folder
os.makedirs(out) # make new output folder
half = device.type != 'cpu' # half precision only supported on CUDA

# Load model
google_utils.attempt_download(weights)
model = torch.load(weights, map_location=device)['model'].float() # load to FP32
# torch.save(torch.load(weights, map_location=device), weights) # update model if SourceChangeWarning
# model.fuse()
model.to(device).eval()
if half:
model.half() # to FP16

# Second-stage classifier
classify = False
if classify:
modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
modelc.to(device).eval()

# Set Dataloader
vid_path, vid_writer = None, None
if webcam:
view_img = True
torch.backends.cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadStreams(source, img_size=imgsz)
else:
save_img = True
dataset = LoadImages(source, img_size=imgsz)

# Get names and colors
names = model.names if hasattr(model, 'names') else model.modules.names
colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]

# Run inference
t0 = time.time()
img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
_ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
for path, img, im0s, vid_cap in dataset:
img = torch.from_numpy(img).to(device)
img = img.half() if half else img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)

# Inference
t1 = torch_utils.time_synchronized()
pred = model(img, augment=opt.augment)[0]

# Apply NMS
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres,
fast=True, classes=opt.classes, agnostic=opt.agnostic_nms)
t2 = torch_utils.time_synchronized()

# Apply Classifier
if classify:
pred = apply_classifier(pred, modelc, img, im0s)

# List to store bounding coordinates of people
people_coords = []

# Process detections
for i, det in enumerate(pred): # detections per image
if webcam: # batch_size >= 1
p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
else:
p, s, im0 = path, '', im0s

save_path = str(Path(out) / Path(p).name)
s += '%gx%g ' % img.shape[2:] # print string
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
if det is not None and len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
s += '%g %ss, ' % (n, names[int(c)]) # add to string

# Write results
for *xyxy, conf, cls in det:
if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file:
file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format

if save_img or view_img: # Add bbox to image
label = '%s %.2f' % (names[int(cls)], conf)
if label is not None:
if (label.split())[0] == 'person':
people_coords.append(xyxy)
# plot_one_box(xyxy, im0, line_thickness=3)
plot_dots_on_people(xyxy, im0)

# Plot lines connecting people
distancing(people_coords, im0, dist_thres_lim=(200,250))

# Print time (inference + NMS)
print('%sDone. (%.3fs)' % (s, t2 - t1))

# Stream results
if view_img:
cv2.imshow(p, im0)
if cv2.waitKey(1) == ord('q'): # q to quit
raise StopIteration

# Save results (image with detections)
if save_img:
if dataset.mode == 'images':
cv2.imwrite(save_path, im0)
else:
if vid_path != save_path: # new video
vid_path = save_path
if isinstance(vid_writer, cv2.VideoWriter):
vid_writer.release() # release previous video writer

fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h))
vid_writer.write(im0)

if save_txt or save_img:
print('Results saved to %s' % os.getcwd() + os.sep + out)
if platform == 'darwin': # MacOS
os.system('open ' + save_path)

print('Done. (%.3fs)' % (time.time() - t0))


if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path')
parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold')
parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
parser.add_argument('--fourcc', type=str, default='mp4v', help='output video codec (verify ffmpeg support)')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--view-img', action='store_true', help='display results')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
opt = parser.parse_args()
opt.img_size = check_img_size(opt.img_size)
print(opt)

with torch.no_grad():
detect()

yolov5.py → yolo_detect_mask.py View File

@@ -309,7 +309,7 @@ def detect(save_img=False):
print('Done. (%.3fs)' % (time.time() - t0)) print('Done. (%.3fs)' % (time.time() - t0))
if __name__ == '__main__': if __name__ == '__main__':
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
parser.add_argument('--weights', nargs='+', type=str, default='best.pt', help='model.pt path(s)')
parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')

Loading…
Cancel
Save