如何将OpenCV与PyQt结合以创建简单的GUI? [英] How to combine OpenCV with PyQt to create a simple GUI?
问题描述
我需要对图像执行很多操作.因此我使用了OpenCV. OpenCV在图像处理方面非常有效,但是提供合适的GUI并不太好.因此,我决定使用PyQt绘制自定义GUI和OpenCV来处理我的图像.
I need to perform lot of operations on an image. So I used OpenCV. OpenCV is very efficient in image processing, however it is not too good to present a suitable GUI. So I decided to use PyQt to draw a custom GUI and OpenCV to process my image.
我创建了一个非常简单的程序,您直接从文档中选择了该程序.我只是读取jpg
图片,然后按s
键将其保存为png
格式.
I created a very simple program you directly picked from the documentation. I simply read a jpg
picture and save it in a png
format by pressing the key s
.
我的目的是将按键s
替换为一个按钮,按下该按钮即可使用PyQt执行相同的操作.另外,我希望PyQt显示的窗口具有与OpenCV相同的行为:主要来说,函数imshow()
显示适合图像尺寸的窗口.
My aim is to replace the key s
with a button to press to perform the same action using PyQt. Also, I want the window displayed by PyQt to have the same behavior as OpenCV: mainly speaking, the function imshow()
displays a window that fits to the image size.
这是我的OpenCV简单代码:
Here is my OpenCV simple code:
import numpy
import cv2
class LoadImage:
def loadImage(self):
img = cv2.imread('photo.jpg')
cv2.imshow('Image on a window',img)
k = cv2.waitKey(0)
if k == 27:
cv2.destroyAllWindows()
elif k == ord('s'):
cv2.imwrite('photopng.png',img)
cv2.destroyAllWindows()
if __name__=="__main__":
LI=LoadImage()
LI.loadImage()
输出:
以下是绘制一个简单窗口的简单PyQt代码:
Here is a simple PyQt code to draw a simple window:
import sys
from PyQt4 import QtGui
class DrawWindow:
def drawWindow(self):
app=QtGui.QApplication(sys.argv)
w=QtGui.QWidget()
#w.resize(250,250)
w.move(300,300)
w.setWindowTitle("Simple Window")
w.show()
sys.exit(app.exec_())
if __name__=="__main__":
DW=DrawWindow()
DW.drawWindow()
如何混合使用这两个代码以达到我的目标?
How can I mix the 2 codes to reach my goal?
推荐答案
基于您的帖子修改了一些代码,我没有使用Opencv来渲染图像,而是使用了QPixmap来渲染图像.然后使用KeyPressEvent捕获用户输入.
Modified some code basing on your post, I didn't use the Opencv to render the image, instead using QPixmap to render it. then use KeyPressEvent to capture the user input .
# -*- coding: utf-8 -*-
import numpy
import cv2
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyDialog(QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
self.cvImage = cv2.imread(r'cat.jpg')
height, width, byteValue = self.cvImage.shape
byteValue = byteValue * width
cv2.cvtColor(self.cvImage, cv2.COLOR_BGR2RGB, self.cvImage)
self.mQImage = QImage(self.cvImage, width, height, byteValue, QImage.Format_RGB888)
def paintEvent(self, QPaintEvent):
painter = QPainter()
painter.begin(self)
painter.drawImage(0, 0, self.mQImage)
painter.end()
def keyPressEvent(self, QKeyEvent):
super(MyDialog, self).keyPressEvent(QKeyEvent)
if 's' == QKeyEvent.text():
cv2.imwrite("cat2.png", self.cvImage)
else:
app.exit(1)
if __name__=="__main__":
import sys
app = QApplication(sys.argv)
w = MyDialog()
w.resize(600, 400)
w.show()
app.exec_()
这篇关于如何将OpenCV与PyQt结合以创建简单的GUI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!