Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to process multiple videos using PyQT5 library in YOLOv5 model? #11870

Closed
1 task
kmsdoit opened this issue Jul 17, 2023 · 3 comments
Closed
1 task
Labels
question Further information is requested Stale

Comments

@kmsdoit
Copy link

kmsdoit commented Jul 17, 2023

Search before asking

Question

this is my code
`import ast
import sys
import cv2
from PySide6.QtWidgets import QApplication, QWidget, QGridLayout, QLabel
from PySide6.QtCore import QThread, Signal, Slot, Qt
from PySide6.QtGui import QImage, QPixmap
import numpy as np
import argparse
import os
import platform
import numpy as np
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

class CameraThread(QThread):
changePixmap = Signal(QPixmap)

def __init__(self, rtsp_link):
    super(CameraThread, self).__init__()
    self.rtsp_link = rtsp_link
    self.is_running = True
    self.device = None

def run(self):
    source = str(self.rtsp_link)
    IMGZ = (640,640)

    device = select_device("0,1")
    data = ROOT / 'data/coco128.yaml'
    model = DetectMultiBackend(weights=ROOT / 'custom_models/ALL_M2.pt', device=device, dnn=False, data = data, fp16=False)
    print("using Device:",self.device)

    stride, names, pt = model.stride, model.names, model.pt
    IMGSZ = check_img_size(IMGZ, s = stride)

    dataset = LoadStreams(source, img_size=IMGZ, stride=stride, auto=pt, vid_stride=1)
    bs = len(dataset)
    model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *IMGSZ))
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())

    for path, im, im0s, vid_cap, s in dataset:
        with dt[0]:
            im = torch.from_numpy(im).to(model.device)
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
            im /= 255  # 0 - 255 to 0.0 - 1.0
            if len(im.shape) == 3:
                im = im[None]  # expand for batch dim

        with dt[1]:
            pred = model(im, augment=False)

        with dt[2]:
            with torch.no_grad():
                pred = non_max_suppression(pred,0.25, 0.45,[5,6], False, max_det=1000)

        for i, det in enumerate(pred):
            seen += 1
            im0, frame = im0s[i].copy(), dataset.count
            annotator = Annotator(im0, line_width=3, example=str(names))
            if len(det):
                det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()

                for *xyxy, conf, cls in reversed(det):
                    c = int(cls)
                    center = (int((xyxy[0] + xyxy[2]) / 2), int((xyxy[1] + xyxy[3]) / 2))
                    label = f'{names[c]} {conf:.2f} {center}'
                    annotator.box_label(xyxy, label, color=colors(c, True))

            im0 = annotator.result()
            ratio_roi = ast.literal_eval(str("[[[ 0.19,0.39],[0.38,0.3],[0.4,0.63],[0.19,0.87]]]"))
            roi = [[[item[0] * im0.shape[1], item[1] * im0.shape[0]] for item in sublist] for sublist in ratio_roi]
            pts1 = np.array(roi, dtype=np.int32)
            # print(pts1)
            cv2.polylines(im0, [pts1], True, (255, 255, 255), 4)
            rgb_image = cv2.cvtColor(im0, cv2.COLOR_BGR2RGB)
            h, w, ch = rgb_image.shape
            bytes_per_line = ch * w
            rgb_image = cv2.resize(rgb_image,(w,h), cv2.INTER_AREA)
            qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(qt_image)
            self.changePixmap.emit(pixmap)



def stop(self):
    self.is_running = False
    self.wait()

class CameraWidget(QLabel):
def init(self, rtsp_link, parent=None):
super(CameraWidget, self).init(parent)
self._pixmap = QPixmap()
self.cameraThread = CameraThread(rtsp_link)
self.cameraThread.changePixmap.connect(self.setVideo)
self.cameraThread.start()

@Slot(QPixmap)
def setVideo(self, image):
    self._pixmap = image
    self.updatePixmap()

def resizeEvent(self, event):
    self.updatePixmap()

def updatePixmap(self):
    if not self._pixmap.isNull():
        pixmap = self._pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio)
        self.setPixmap(pixmap)

class MyApp(QWidget):
def init(self, rtsp_links):
super().init()
self.rtsp_links = rtsp_links
self.initUI()

def initUI(self):
    grid = QGridLayout()
    self.setLayout(grid)
    for i, rtsp_link in enumerate(self.rtsp_links):
        camera_widget = CameraWidget(rtsp_link)
        grid.addWidget(camera_widget, i//4, i%4)
    self.setWindowTitle('Camera Viewer')
    self.resize(1920, 1080)
    self.show()

if name == 'main':
rtsp_addresses = ['rtsp1','rtsp2','rtsp3','rtsp4','rtsp5','rtsp6','rtsp7','rtsp8']
app = QApplication(sys.argv)
ex = MyApp(rtsp_addresses)
sys.exit(app.exec_())
`

If you run this code and you run the device with cpu, you run it well, but if you run with gpu, you can see a screen or two and it stops I'd appreciate it if you could tell me what the problem is

Additional

No response

@kmsdoit kmsdoit added the question Further information is requested label Jul 17, 2023
@github-actions
Copy link
Contributor

github-actions bot commented Jul 17, 2023

👋 Hello @kmsdoit, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our Tips for Best Training Results.

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

YOLOv5 CI

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training, validation, inference, export and benchmarks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

Introducing YOLOv8 🚀

We're excited to announce the launch of our latest state-of-the-art (SOTA) object detection model for 2023 - YOLOv8 🚀!

Designed to be fast, accurate, and easy to use, YOLOv8 is an ideal choice for a wide range of object detection, image segmentation and image classification tasks. With YOLOv8, you'll be able to quickly and accurately detect objects in real-time, streamline your workflows, and achieve new levels of accuracy in your projects.

Check out our YOLOv8 Docs for details and get started with:

pip install ultralytics

@glenn-jocher
Copy link
Member

@kmsdoit hi,

Based on your code, it appears that you are using the PyQT5 library to process multiple videos with the YOLOv5 model. It is possible to use the PyQT5 library in conjunction with the YOLOv5 model for video processing.

However, regarding the issue you mentioned where the code stops when running with a GPU, it is likely that there is a problem related to GPU utilization or compatibility. To further investigate and diagnose the problem, it would be helpful to provide additional information such as error messages or log files.

Please ensure that you have the necessary GPU drivers, CUDA, and cuDNN installed and compatible with the version of PyTorch and YOLOv5 you are using. Additionally, make sure that your GPU is properly recognized and utilized by the code.

If you are still experiencing difficulties, it may be helpful to consult the YOLOv5 documentation, or seek assistance from the YOLOv5 GitHub community, where fellow developers and contributors can provide more specific guidance.

Hope this helps! Let me know if you have any further questions.

@github-actions
Copy link
Contributor

👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.

For additional resources and information, please see the links below:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLO 🚀 and Vision AI ⭐

@github-actions github-actions bot added the Stale label Aug 17, 2023
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Aug 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested Stale
Projects
None yet
Development

No branches or pull requests

2 participants