camera.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from PyQt5.QtCore import QThread # 引入多线程,设备是多个,一个设备一个任务
  2. import cv2
  3. import numpy as np
  4. from ultralytics import YOLO # 1
  5. # from cv2 import VideoCapture
  6. # 1. 定义信号(引入)
  7. from PyQt5.QtCore import pyqtSignal
  8. class CameraDev(QThread):
  9. # 定义信号(定义)
  10. sig_video = pyqtSignal(bytes, int, int, int) # 信号传递的数据(图像的二进制数据,字节序列(bytes), 图像高度int,宽度int,通道数int)
  11. def __init__(self):
  12. super(CameraDev, self).__init__()
  13. # 开始视频抓取的任务初始化
  14. # 初始化摄像头
  15. self.cam = cv2.VideoCapture(
  16. 0, # 摄像头的编号,从0
  17. cv2.CAP_DSHOW # 视频的处理调用DirectX 3D (DirectShow)
  18. )
  19. self.isOver = False
  20. self.model = YOLO("mods/best.pt") # 2
  21. def run(self):
  22. # kernel = np.array([ # 深度学习就是找到一个kernel是的特征对分类有效
  23. # [0, -2, 0],
  24. # [-2, 8, -2],
  25. # [0, -2, 0]
  26. # ])
  27. # 设备线程的任务,run结束,则任务结束
  28. while not self.isOver:
  29. # 反复抓取视频处理
  30. # print("设备准备工作!")
  31. status, img = self.cam.read() # 从摄像头读取图像
  32. if status:
  33. # print(img.shape)
  34. # 显示图像
  35. # 调用人工智能模块,进行图像识别(处理)
  36. # img = cv2.GaussianBlur(img, (3, 3), 2.0)
  37. # img = cv2.filter2D(img, -1, kernel, delta=200.0)
  38. result = self.model(img) # 3
  39. # 处理结果 # 4
  40. boxes = result[0].boxes
  41. names = result[0].names
  42. if len(boxes) >= 1:
  43. cls = int(boxes.cls[0].cpu().item())
  44. conf = boxes.conf[0].cpu().item()
  45. x1, y1, x2, y2 = boxes.xyxy[0].cpu().numpy().astype(np.int32)
  46. # 标注:目标区域,名字,概率
  47. img = cv2.rectangle(img, (x1, y1), (x2, y2), color=(0, 0, 255), thickness=5)
  48. img = cv2.putText(img, F"{names[cls]}:{conf:.2f}", (x1, y1), 0, 3, color=(255, 0, 0), thickness=3)
  49. # 2. 发送信号
  50. self.sig_video.emit(img.tobytes(), img.shape[0], img.shape[1], img.shape[2])
  51. QThread.usleep(100000) # 1000000微秒 = 1秒
  52. def close(self):
  53. # 停止多任务
  54. self.isOver = True
  55. while self.isRunning():
  56. pass
  57. print("线程终止")
  58. # 释放设备
  59. self.cam.release()
  60. print("设备释放")