I have a program that involves both pyQt and opencv. I installed opencv with anaconda and installed pyqt separately a while ago. I run anaconda python2.7 on an OSX machine.
The example code is below, it is supposed to have a button that switch on openCV camera, and put the image to self.video_frame
, which is a QLable()
from PyQt4 import QtGui
from PyQt4.QtGui import QImage,QPixmap
import PyQt4.QtCore as QtCore
import cv2,sys, time
class QtCapture(QtGui.QWidget):
def __init__(self, *args):
self.app = QtGui.QApplication(sys.argv)
super(QtGui.QWidget, self).__init__()
self.layout = QtGui.QGridLayout()
self.w = QtGui.QWidget() # Main gui object
self.w.setMinimumHeight(480)
self.capture = None
self.frame = None
self.video_frame = QtGui.QLabel()
self.button_start = QtGui.QPushButton('Camera Connect')
self.button_start.setFixedWidth(300)
self.button_start.clicked.connect(lambda: self.start())
self.w.setLayout(self.layout)
self.layout.addWidget(self.button_start, 0, 0)
self.layout.addWidget(self.video_frame, 0, 1, 16, 1)
self.w.show()
print "Init"
def nextFrameSlot(self):
try:
previous_frame = self.current_frame
ret, self.frame = self.cap.read()
self.current_frame = self.frame
frame_diff = cv2.absdiff(self.current_frame, previous_frame)
qformat= QImage.Format_Indexed8
if len(self.frame.shape) == 3:
if self.frame.shape[2] == 4:
qformat=QImage.Format_RGBA8888
else:
qformat=QImage.Format_RGB888
img = QtGui.QImage(self.frame, self.frame.shape[1], self.frame.shape[0], self.frame.strides[0], qformat)
self.video_frame.setPixmap(QtGui.QPixmap.fromImage(img))
self.video_frame.setScaledContents(True)
except Exception, e:
print "Failed"
self.timer.stop()
def start(self):
print "button_start pressed. "
try:
self.cap = cv2.VideoCapture(0)
self.start_time = time.time()
self.timer = QtCore.QTimer()
ret, self.current_frame = self.cap.read()
self.timer.timeout.connect(self.nextFrameSlot)
self.timer.start(1./10.)
except Exception, e:
print "failed"
def closeEvent(self, event):
print "Closing"
self.deleteLater()
def deleteLater(self):
print('closed')
self.cap.release()
super(QtGui.QWidget, self).deleteLater()
def main():
#calibration_pts = getCalibrationCoordinates(cameraChoice)
sozen = QtCapture()
sys.exit(sozen.app.exec_())
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
I got the following message along with all other QCocoa classes:
Class QCocoaMenu is implemented in both
/Users/myname/anaconda/lib/libQtGui.4.8.7.dylib (0x104a7c150)
and /Users/myname/anaconda/lib/python2.7/site-packages/cv2/.dylibs/QtGui (0x107b6a120).
One of the two will be used. Which one is undefined.
The program also crashes with Abort trap: 6
.
Please advice if you know what might happen there?