我需要在python

时间:2017-05-04 07:26:38

标签: python screenshot

import gi
from gi.repository import Gtk,Gdk   
from gi.repository.GdkPixbuf import Pixbuf, InterpType
from PIL import Image
import inspect
window = Gdk.get_default_root_window()
pb = Gdk.pixbuf_get_from_window(window, 840,380,240,230)
height=pb.get_height()
width=pb.get_width()
#print pb.get_pixels()
im = Image.frombuffer("RGB", (width,height) ,pb.get_pixels(), 'raw', 'RGB', 0, 1)
im.save('f.png')

这是我在python中捕获截图的代码。 我需要它来通过处理这个镜头给我的图像在电脑上玩游戏。 但我的问题是它对于玩游戏来说太慢了。 所以我需要一个非常快速的方法来捕获至少25 fps

2 个答案:

答案 0 :(得分:0)

下面的代码是截取pyside的示例代码。少量编辑可以帮助您获得结果。

#!/usr/bin/env python

#############################################################################
##
## Copyright (C) 2005-2005 Trolltech AS. All rights reserved.
##
## This file is part of the example classes of the Qt Toolkit.
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file.  Please review the following information to ensure GNU
## General Public Licensing requirements will be met:
## http://www.trolltech.com/products/qt/opensource.html
##
## If you are unsure which license is appropriate for your use, please
## review the following information:
## http://www.trolltech.com/products/qt/licensing.html or contact the
## sales department at sales@trolltech.com.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
#############################################################################

from PySide import QtCore, QtGui


class Screenshot(QtGui.QWidget):
    def __init__(self):
        super(Screenshot, self).__init__()

        self.screenshotLabel = QtGui.QLabel()
        self.screenshotLabel.setSizePolicy(QtGui.QSizePolicy.Expanding,
                QtGui.QSizePolicy.Expanding)
        self.screenshotLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.screenshotLabel.setMinimumSize(240, 160)

        self.createOptionsGroupBox()
        self.createButtonsLayout()

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.screenshotLabel)
        mainLayout.addWidget(self.optionsGroupBox)
        mainLayout.addLayout(self.buttonsLayout)
        self.setLayout(mainLayout)

        self.shootScreen()
        self.delaySpinBox.setValue(5)

        self.setWindowTitle("Screenshot")
        self.resize(300, 200)

    def resizeEvent(self, event):
        scaledSize = self.originalPixmap.size()
        scaledSize.scale(self.screenshotLabel.size(), QtCore.Qt.KeepAspectRatio)
        if not self.screenshotLabel.pixmap() or scaledSize != self.screenshotLabel.pixmap().size():
            self.updateScreenshotLabel()

    def newScreenshot(self):
        if self.hideThisWindowCheckBox.isChecked():
            self.hide()
        self.newScreenshotButton.setDisabled(True)

        QtCore.QTimer.singleShot(self.delaySpinBox.value() * 1000,
                self.shootScreen)

    def saveScreenshot(self):
        format = 'png'
        initialPath = QtCore.QDir.currentPath() + "/untitled." + format

        fileName,_ = QtGui.QFileDialog.getSaveFileName(self, "Save As",
                initialPath,
                "%s Files (*.%s);;All Files (*)" % (format.upper(), format))
        if fileName:
            self.originalPixmap.save(fileName, format)

    def shootScreen(self):
        if self.delaySpinBox.value() != 0:
            QtGui.qApp.beep()

        # Garbage collect any existing image first.
        self.originalPixmap = None
        self.originalPixmap = QtGui.QPixmap.grabWindow(QtGui.QApplication.desktop().winId())
        self.updateScreenshotLabel()

        self.newScreenshotButton.setDisabled(False)
        if self.hideThisWindowCheckBox.isChecked():
            self.show()

    def updateCheckBox(self):
        if self.delaySpinBox.value() == 0:
            self.hideThisWindowCheckBox.setDisabled(True)
        else:
            self.hideThisWindowCheckBox.setDisabled(False)

    def createOptionsGroupBox(self):
        self.optionsGroupBox = QtGui.QGroupBox("Options")

        self.delaySpinBox = QtGui.QSpinBox()
        self.delaySpinBox.setSuffix(" s")
        self.delaySpinBox.setMaximum(60)
        self.delaySpinBox.valueChanged.connect(self.updateCheckBox)

        self.delaySpinBoxLabel = QtGui.QLabel("Screenshot Delay:")

        self.hideThisWindowCheckBox = QtGui.QCheckBox("Hide This Window")

        optionsGroupBoxLayout = QtGui.QGridLayout()
        optionsGroupBoxLayout.addWidget(self.delaySpinBoxLabel, 0, 0)
        optionsGroupBoxLayout.addWidget(self.delaySpinBox, 0, 1)
        optionsGroupBoxLayout.addWidget(self.hideThisWindowCheckBox, 1, 0, 1, 2)
        self.optionsGroupBox.setLayout(optionsGroupBoxLayout)

    def createButtonsLayout(self):
        self.newScreenshotButton = self.createButton("New Screenshot",
                self.newScreenshot)

        self.saveScreenshotButton = self.createButton("Save Screenshot",
                self.saveScreenshot)

        self.quitScreenshotButton = self.createButton("Quit", self.close)

        self.buttonsLayout = QtGui.QHBoxLayout()
        self.buttonsLayout.addStretch()
        self.buttonsLayout.addWidget(self.newScreenshotButton)
        self.buttonsLayout.addWidget(self.saveScreenshotButton)
        self.buttonsLayout.addWidget(self.quitScreenshotButton)

    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.clicked.connect(member)
        return button

    def updateScreenshotLabel(self):
        self.screenshotLabel.setPixmap(self.originalPixmap.scaled(
                self.screenshotLabel.size(), QtCore.Qt.KeepAspectRatio,
                QtCore.Qt.SmoothTransformation))


if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    screenshot = Screenshot()
    screenshot.show()
    sys.exit(app.exec_())

答案 1 :(得分:0)

我根据您的要求编写了程序。它在同一目录中创建文件夹Capture。 Png图像将保存在" Capture"文件夹中。

如果您需要超过25fps,我建议使用OBS软件。

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'ScreenCapture.ui'
#
# Created: Sat May 06 15:32:13 2017
#      by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!

from PySide import QtCore, QtGui

class Ui_ScreenCapture(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self.CreateCaptureFolder()

    def setupUi(self, ScreenCapture):
        ScreenCapture.setObjectName("ScreenCapture")
        ScreenCapture.resize(180, 90)
        self.verticalLayout = QtGui.QVBoxLayout(ScreenCapture)
        self.verticalLayout.setObjectName("verticalLayout")
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.start = QtGui.QPushButton(ScreenCapture)
        self.start.setObjectName("start")
        self.gridLayout.addWidget(self.start, 1, 0, 1, 1)
        #self.stop = QtGui.QPushButton(ScreenCapture)
        #self.stop.setObjectName("stop")
        #self.gridLayout.addWidget(self.stop, 1, 1, 1, 1)
        self.sbfps = QtGui.QSpinBox(ScreenCapture)
        self.sbfps.setPrefix("")
        self.sbfps.setMinimum(1)
        self.sbfps.setMaximum(60)
        self.sbfps.setObjectName("sbfps")
        self.gridLayout.addWidget(self.sbfps, 0, 1, 1, 1)
        self.label = QtGui.QLabel(ScreenCapture)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout)

        self.retranslateUi(ScreenCapture)
        QtCore.QMetaObject.connectSlotsByName(ScreenCapture)

    def retranslateUi(self, ScreenCapture):
        ScreenCapture.setWindowTitle(QtGui.QApplication.translate("ScreenCapture", "Screen Capture", None, QtGui.QApplication.UnicodeUTF8))
        self.start.setText(QtGui.QApplication.translate("ScreenCapture", "Start", None, QtGui.QApplication.UnicodeUTF8))
        #self.stop.setText(QtGui.QApplication.translate("ScreenCapture", "Stop", None, QtGui.QApplication.UnicodeUTF8))
        self.sbfps.setSuffix(QtGui.QApplication.translate("ScreenCapture", " fps", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("ScreenCapture", "Screen Shot FPS", None, QtGui.QApplication.UnicodeUTF8))
###########################################################################
        self.fname = 1
        self.start.clicked.connect(self.loop)
###########################################################################
    def CreateCaptureFolder(self):
        if QtCore.QDir("Capture").exists():
            print "Folder Exists"
            pass
        else:
            print "Capture folder not exists"
            QtCore.QDir().mkdir("Capture")
            print "Created folder capture"

    def Capture(self):
        self.start.setEnabled(False)
        self.originalPixmap = None
        self.originalPixmap = QtGui.QPixmap.grabWindow(QtGui.QApplication.desktop().winId())    
        format = 'png'
        initialPath = QtCore.QDir.currentPath() + "/Capture/"

        fileName = initialPath + str(self.fname) + '.' + format

        if fileName:
            self.originalPixmap.save(fileName, format)

        self.fname+=1

    def loop(self):
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(False)
        self.timer.timeout.connect(self.Capture)
        self.timer.start(1000/self.sbfps.value())

    def stop(self):
        self.timer.stop() 

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    if not app:
        app = QtGui.QApplication(sys.argv)
    ui = Ui_ScreenCapture()
    ui.show()
    sys.exit(app.exec_())