using OpenCV in Qt4 GUI using python

copyright (C) 2011-2017 iesensor.com

This python read from webcam and display into Qt4 widget(not highGUI) code is adapted from example code from : #http://wrdeoftheday.com/?page_id=2

since not all source code is attached, I complete the code and make it available for downland. This can serve as a better starting point for more complicated app.

zip password: iesensor.com

zip file:  qtcvpy

import sys
import cv2
import numpy as np
from PyQt4 import QtGui, QtCore, Qt
from ui import Ui_MainWindow

#D:\vbshare\Codes\opencv\qtcvpy>D:\vbshare\Python27\Lib\site-packages\PyQt4\pyuic4.bat mainWindow.ui -o ui.py

class Video():
def __init__(self,capture):
self.capture = capture
self.currentFrame=np.array([])

def captureNextFrame(self):
“””
capture frame and reverse RBG BGR and return opencv image
“””
ret, readFrame=self.capture.read()
if(ret==True):
self.currentFrame=cv2.cvtColor(readFrame,cv2.COLOR_BGR2RGB)

def convertFrame(self):
“””     converts frame to format suitable for QtGui            “””
try:
height,width=self.currentFrame.shape[:2]
img=QtGui.QImage(self.currentFrame,
width,
height,
QtGui.QImage.Format_RGB888)
img=QtGui.QPixmap.fromImage(img)
self.previousFrame = self.currentFrame
return img
except:
return None

class Gui(QtGui.QMainWindow):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.video = Video(cv2.VideoCapture(0))
self._timer = QtCore.QTimer(self)
self._timer.timeout.connect(self.play)
self._timer.start(27)
self.update()

def play(self):
try:
self.video.captureNextFrame()
self.ui.videoFrame.setPixmap(
self.video.convertFrame())
self.ui.videoFrame.setScaledContents(True)
except TypeError:
print “No frame”

def main():
app = QtGui.QApplication(sys.argv)
ex = Gui()
ex.show()
sys.exit(app.exec_())

if __name__ == ‘__main__’:
main()

BSD documentation licensed Free for non-commercial usage only
Author: Qingfeng XIA
copyright (C) 2011-2017
http://www.iesensor.com
please keep the original link in your reference.
http://www.iesensor.com/blog/2014/06/15/using-opencv-in-qt4-gui-using-python/
This entry was posted in Programming. Bookmark the permalink.