Skip to content
The Chat Archive
gpt-4-0314· OpenAI WildChat-4.8M (AI2)

соедини import cv2 import numpy as np import cvzone import math import tensorflow as tf…

  1. User

    соедини import cv2 import numpy as np import cvzone import math import tensorflow as tf from tensorflow.keras.models import load_model

    Загрузка модели для детектирования людей

    human_net = cv2.dnn.readNetFromCaffe('human.prototxt', 'human.caffemodel')

    Загрузка модели для детектирования одежды на людях

    model = load_model('trained_model.h5')

    Загрузка видеопотока

    cap = cv2.VideoCapture(0) while True: # Чтение кадра из видеопотока ret, frame = cap.read() # Детектирование людей на кадре human_blob = cv2.dnn.blobFromImage(frame, 1/255, (416, 416), swapRB=True, crop=False) human_net.setInput(human_blob) human_detections = human_net.forward() # Детектирование одежды на кадре for i in range(human_detections.shape[2]): confidence = human_detections[0, 0, i, 2] if confidence > 0.5: x1 = int(human_detections[0, 0, i, 3] * frame.shape[1]) y1 = int(human_detections[0, 0, i, 4] * frame.shape[0]) x2 = int(human_detections[0, 0, i, 5] * frame.shape[1]) y2 = int(human_detections[0, 0, i, 6] * frame.shape[0]) clothes_blob = cv2.dnn.blobFromImage(frame[y1:y2, x1:x2], 1/255, (416, 416), swapRB=True, crop=False) model.setInput(clothes_blob) clothes_detections = model.forward() for j in range(clothes_detections.shape[2]): confidence = clothes_detections[0, 0, j, 2] if confidence > 0.5: x1_c = int(clothes_detections[0, 0, j, 3] * (x2 - x1) + x1) y1_c = int(clothes_detections[0, 0, j, 4] * (y2 - y1) + y1) x2_c = int(clothes_detections[0, 0, j, 5] * (x2 - x1) + x1) y2_c = int(clothes_detections[0, 0, j, 6] * (y2 - y1) + y1) cv2.rectangle(frame, (x1_c, y1_c), (x2_c, y2_c), (255, 0, 0), 2) cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Отображение кадра cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() с кодом import argparse import os import platform import sys from pathlib import Path

    import torch

    FILE = Path(file).resolve() ROOT = FILE.parents[0] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative

    from models.common import DetectMultiBackend from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2, increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh) from utils.plots import Annotator, colors, save_one_box from utils.torch_utils import select_device, smart_inference_mode @smart_inference_mode() def run( weights=ROOT / 'yolov5s.pt', # model path or triton URL source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam) data=ROOT / 'data/coco128.yaml', # dataset.yaml path imgsz=(640, 640), # inference size (height, width) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=ROOT / 'runs/detect', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference vid_stride=1, # video frame-rate stride ): source = str(source) save_img = not nosave and not source.endswith('.txt') # save inference images is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file) screenshot = source.lower().startswith('screen') if is_url and is_file: source = check_file(source) # download # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) stride, names, pt = model.stride, model.names, model.pt imgsz = check_img_size(imgsz, s=stride) # check image size # Dataloader bs = 1 # batch_size if webcam: view_img = check_imshow(warn=True) dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) bs = len(dataset) elif screenshot: dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt) else: dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride) vid_path, vid_writer = [None] * bs, [None] * bs # Run inference model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup seen, windows, dt = 0, [], (Profile(), Profile(), Profile()) for path, im, im0s, vid_cap, s in dataset: with dt[0]:

  2. Assistant

    im = torch.from_numpy(im).to(device) # inference tensor im = im.half() if half else im.float() # half precision im /= 255.0 # 0-255 to 0.0-1.0 s, t = s.numpy(), im.shape # index, shape

        # Inference
        with dt[1]:
            if pt:
                # Fast inference
                pred = model(im, augment=augment)[0]
            else:
                # PyTorch Detections
                pred = model(im, augment=augment, visualize=visualize)[0]
    
        # Non-maximum suppression
        with dt[2]:
            pred = non_max_suppression(
                pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det, multi_label=True
            )
    
        # Process detections
        for i, det in enumerate(pred):  # detections per image
            seen += 1
            p, s = path[i], im0s[:, :, :, i].shape
    
            # Save results (image with detections)
            if save_img or view_img:
                annotator = Annotator(im0s[:, :, :, i], name=names if hide_conf else None, line_width=line_thickness)
                color = None
                for *xyxy, conf, cls in det:
                    # Add bbox to image
                    c = int(cls)
                    color = annotator.box_label(xyxy, conf, names[c], color=color, hide_labels=hide_labels)
                    # Plot landmarks
                    if visualize:
                        cls_data = classes, names
                        annotator.landmark(xyxy, visualize, color, cls_data)
    
                # Stream results
                if view_img:
                    cv2.imshow(str(s), im0s[:, :, :, i])
                    delay = 1  # minimum time per-frame
                    k = cv2.waitKey(delay) & 0xFF  # 0xFF == ord(255)
                    if k == ord("q"):  # q: quit
                        raise StopIteration
                    elif k == ord("s"):  # s: save
                        save_one_box(xyxy, im0s, file=save_dir / "temp.jpg", gain=s)
                        print("Image saved to `%s`" % save_dir)
                    if screens:  # quit after 1 screen
                        break
    
                # Save image
                if save_img:
                    cv2.imwrite(str(save_dir / p.name), annotator.result())
    
            # Save *.txt labels
            if save_txt:
                save_one_box(xyxy, None, file=save_dir / "labels" / f"{p.stem}.txt", write=save_conf)
    
            # Logging
            if i == 0 and t:
                LOGGER.info(
                    f"{path}  ({s[0]:g}x{s[1]:g}) done in {dt[2].delta * 1e3:.1f}ms: {colors(c)}{p.stem}{colorstr()}"
                )
    
    LOGGER.info(
        f"Processed {seen} image{'s,' if seen > 1 else ','} {dataset.n_within_stride - seen} not in stride."
    )
    LOGGER.info(
        f"Done. ({weights.stem or 'inference'} RT: {100 * dt[2].rate:.1f}ms," f"LT: {100 * dt.loops.mean():.1f}ms)"
    )
    
    if save_img:
        LOGGER.info(f"Results saved to %s\n", save_dir)
    
    if view_img and not (webcam or screens):
        LOGGER.info(f"Images displayed in %g seconds.\n", dt.imshow)
    

    try: app.run() except (StopIteration, KeyboardInterrupt): sys.exit()

    For prettifying the code, you can simply reformat and adjust the indentation as follows:

    First, remove the unnecessary imports and move the necessary imports to the beginning of the file:

    import sys
    from pathlib import Path
    import torch
    from models.common import DetectMultiBackend
    from utils.dataloaders import LoadImages, LoadScreenshots, LoadStreams
    from utils.general import (non_max_suppression,)
    from utils.torch_utils import select_device, smart_inference_mode
    

    Then, adjust the indentation of the code block inside the run function to match the try-except block:

    source = str(source)
    ... (lines truncated) ...
        source = check_file(source)  # download
    
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir
    
    device = select_device(device)
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
    stride, names, pt = model.stride, model.names, model.pt
    imgsz = check_img_size(imgsz, s=stride)  # check image size
    bs = 1  # batch_size
    
    ... (lines truncated) ...
        if view_img and not (webcam or screens):
            LOGGER.info(f"Images displayed in %g seconds.\n", dt.imshow)
    
    try:
        app.run()
    except (StopIteration, KeyboardInterrupt):
        sys.exit()
    

    This should result in a cleaner, easier-to-read code block with the proper imports and indentation.