opencv 在我的屏幕上使用自定义yolov7训练模型

m528fe3b  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(244)

我知道的
我已经使用yolov 7-tiny训练了一个自定义模型
我现在尝试使用它在屏幕上进行对象检测
剧本我有:

import mss
import numpy as np
import cv2
import time
import keyboard
import torch
from hubconf import custom

model = custom(path_or_model='yolov7-tiny-custom.pt')

with mss.mss() as sct:
    monitor = {'top': 30, 'left': 0, 'width': 1152, 'height': 864}
while True:
    t = time.time()

    img = np.array(sct.grab(monitor))

    results = model(img)

    cv2.imshow('s', np.squeeze(results.render()))

    print('fps: {}'.format(1 / (time.time() - t)))

    cv2.waitKey(1)

    if keyboard.is_pressed('q'):
        break

cv2.destroyAllWindows()

问题是

我知道在那个脚本中一切都正常,但是当它最终检测到一个对象时,它想在屏幕上画一个矩形。
我收到以下错误:

Traceback (most recent call last):
  File "c:\Users\ahmed\Desktop\PC\Repos\yolov7-custom\yolov7-custom\aimbot.py", line 20, in <module>
    cv2.imshow('s', np.squeeze(results.render()))
  File "c:\Users\ahmed\Desktop\PC\Repos\yolov7-custom\yolov7-custom\models\common.py", line 990, in render
    self.display(render=True)  # render results
  File "c:\Users\ahmed\Desktop\PC\Repos\yolov7-custom\yolov7-custom\models\common.py", line 964, in display
    plot_one_box(box, img, label=label, color=colors[int(cls) % 10])
  File "c:\Users\ahmed\Desktop\PC\Repos\yolov7-custom\yolov7-custom\utils\plots.py", line 62, in plot_one_box
    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'rectangle'
> Overload resolution failed:
>  - Layout of the output array img is incompatible with cv::Mat
>  - Expected Ptr<cv::UMat> for argument 'img'
>  - argument for rectangle() given by name ('thickness') and position (4)
>  - argument for rectangle() given by name ('thickness') and position (4)

摘要

我不太清楚这里发生了什么,但我相信当我截图时,我把它转换成了一个数组并应用了我的模型。当它想画一个矩形时,它无法做到,因为输出数组img与OpenCV矩阵不兼容。我该如何解决这个问题?

c6ubokkw

c6ubokkw1#

我尝试重现您的问题,并将您的代码与一个可用的yolo-demo合并,但我找不到任何会返回类似问题中的错误信息的问题。您可以在您的环境中检查它:

import mss
import numpy as np
import cv2
import torch
import time

model = torch.hub.load('ultralytics/yolov5', 'yolov5s')

with mss.mss() as sct:
    monitor = {'top': 50, 'left': 50, 'width': 600, 'height': 400}

    while True:
        t = time.time()

        img = np.array(sct.grab(monitor))
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        results = model(img)
        results.render()
        out = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        cv2.imshow('s', out)

        print('fps: {}'.format(1 / (time.time() - t)))

        if cv2.waitKey(1) == 27:
            break

cv2.destroyAllWindows()

输出量:

相关问题