OpenCV是一個基於BSD許可(開源)發行的跨平臺計算機視覺庫,可以運行在Linux、Windows、Android和Mac OS作業系統上,
使用起來十分方便,把它與PyQt結合起來,就可以順利的操作視頻、圖像了。具體安裝請自行百度,這裡介紹使用方法。
一、python中opencv打開圖像方法:
import cv2
filename='dog.jpg'
img=cv2.imread(filename)
cv2.imshow('Main Window',img)
cv2.waitKey() #任意鍵退出
cv2.destroyAllWindows()
二、python中用opencv打開視頻頭的方法:
import cv2
cap=cv2.VideoCapture(0)
success, frame=cap.read()
while success and cv2.waitKey(1)==-1:
cv2.imshow("Main Window", frame)
success, frame=cap.read()
cap.release()
cv2.destroyAllWindows()
三、利用PyQt 的QLabel顯示視頻:
#藉助QTimer,不斷產生事件,顯示圖片
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import cv2
from Ui_main import Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.timer_camera = QTimer(self)
self.cap = cv2.VideoCapture(0)
self.timer_camera.timeout.connect(self.show_pic)
self.timer_camera.start(10)
def show_pic(self):
success, frame=self.cap.read()
if success:
show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
showImage = QImage(show.data, show.shape[1], show.shape[0], QImage.Format_RGB888)
self.label.setPixmap(QPixmap.fromImage(showImage))
self.timer_camera.start(10)
if __name__=='__main__':
import sys
app=QApplication(sys.argv)
window=MainWindow()
window.show()
sys.exit(app.exec_())