Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. OpenCV2 Qt Quick Python
Forum Update on Monday, May 27th 2025

OpenCV2 Qt Quick Python

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
3 Posts 1 Posters 658 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Minhtam
    wrote on last edited by
    #1

    Hi everyone!
    I wonder why there is no simple example to stream the cv2.videocapture(camera/videopath) frame to Qt Quick Python? (There are a lot of samples on QWidget but it is ugly) There are many projects with the output cv2.imshow(frame) like YOLOv5,v6,v7 object detection, and so on. I cannot find any example that works on QML+Python that could work instantly for quicker development. Please share with me if you have any examples. Thank you in advance <3

    Screenshot from 2022-12-13 22-38-55.png

    1 Reply Last reply
    0
    • M Offline
      M Offline
      Minhtam
      wrote on last edited by
      #2

      community is cold

      here my embrace

      # This Python file uses the following encoding: utf-8
      import datetime
      import os
      import sys
      from pathlib import Path
      import cv2
      from PySide6.QtCore import QObject, Slot, QTimer, Signal, QThread, Qt
      from PySide6.QtGui import QGuiApplication, QImage
      from PySide6.QtQml import QQmlApplicationEngine
      from PySide6.QtQuick import QQuickImageProvider
      
      
      class CameraThread(QThread):
          updateFrame = Signal(QImage)
          def __init__(self, parent=None):
              QThread.__init__(self, parent)
      
          def run(self):
              self.cap = cv2.VideoCapture(0, apiPreference=cv2.CAP_ANY, params=[
              cv2.CAP_PROP_FRAME_WIDTH, 1280,
              cv2.CAP_PROP_FRAME_HEIGHT, 720])
              while self.cap.isOpened():
                  print("Camera Thread working")
                  ret, frame = self.cap.read()
                  if not ret:
                      print("holy banana")
                      pass
                  color_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                  print(color_frame.shape[1])
                  print(color_frame.shape[0])
                  img = QImage(color_frame.data, color_frame.shape[1], color_frame.shape[0], QImage.Format_RGB888)
                  self.updateFrame.emit(img)
          def stop(self):
                  self.ThreadActive = False
                  self.quit()
      
      class CamProvider(QQuickImageProvider):
          image = None
      
          def __init__(self):
              super(CamProvider, self).__init__(QQuickImageProvider.Image)
              self.cam = CameraThread()
              self.cam.updateFrame.connect(self.update_image)
      
          def requestImage(self, id, size, requestedSize):
              if id == "img?id=false" or "img?id=true":
                  if self.image:
                      img = self.image
                  else:
                      img = QImage(1280, 720, QImage.Format_RGBA8888)
                      img.fill(Qt.black)
              return img
      
          imageChanged = Signal(bool)
          cameraError = Signal(bool)
      
          @Slot()
          def update_image(self, img):
              self.imageChanged.emit(True)
              self.image = img
      
          @Slot()
          def start(self):
              try:
                  self.cam.start()
                  print("Starting...")
              except:
                  self.cameraError.emit(True)
      
          @Slot()
          def stop(self):
              self.cam.cap.release()
              self.cam.stop()
              print("Finishing...")
      
      
      class MainWindow(QObject):
      
          def __init__(self):
              QObject.__init__(self)
              self.timer = QTimer()
              self.timer.timeout.connect(lambda: self.setTime())
              self.timer.start(1000)
      
          signal_time = Signal(str)
      
          @Slot(str)
          def setTime(self):
              global date
              now = datetime.datetime.now()
              date = now.strftime("%02H:%M")
              self.signal_time.emit(date)
      
      if __name__ == "__main__":
          app = QGuiApplication(sys.argv)
          engine = QQmlApplicationEngine()
      
          # Get Context (Link between backend python and frontend QML)
          main = MainWindow()
          engine.rootContext().setContextProperty("backend", main)
          #Camera
          camProvider = CamProvider()
          engine.rootContext().setContextProperty("camProvider", camProvider)
          engine.addImageProvider("camProvider", camProvider)
      
          engine.load(os.fspath(Path(__file__).resolve().parent / "qml/main.qml"))
          if not engine.rootObjects():
              sys.exit(-1)
          sys.exit(app.exec_())
      
      
      1 Reply Last reply
      1
      • M Offline
        M Offline
        Minhtam
        wrote on last edited by
        #3

        @Minhtam said in OpenCV2 Qt Quick Python:

          self.cap = cv2.VideoCapture(0, apiPreference=cv2.CAP_ANY, params=[
            cv2.CAP_PROP_FRAME_WIDTH, 1280,
            cv2.CAP_PROP_FRAME_HEIGHT, 720])
        

        well, I just found a solution and then apply for little Jetson Nano but can not get it from pip. Then I try to build from source PySide6 but again "Qt for small business" cold again

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved