我正在尝试使用 Python(2.7 或 2.6 版)和 PyObjC(2.2 版)从 Macbook Pro 内置的 Apple iSight 摄像头捕获单帧。
作为起点,我使用了这个旧的 StackOverflow问题。为了验证它是否有意义,我交叉引用了它似乎基于的Apple 的 MyRecorder示例。不幸的是,我的脚本不起作用。
我的大问题是:
- 我是否正确初始化相机?
- 我是否正确启动了事件循环?
- 我应该做任何其他设置吗?
在下面粘贴的示例脚本中,预期的操作是在调用 startImageCapture() 之后,我应该开始打印来自 CaptureDelegate 的“Got a frame...”消息。但是,相机的灯永远不会打开,并且代理的回调永远不会执行。
另外,在startImageCapture()过程中没有失败,所有函数都声称成功,并且成功找到了iSight设备。分析 pdb 中的 session 对象表明它具有有效的输入和输出对象,输出分配了一个委托,该设备没有被其他进程使用,并且在调用 startRunning() 后会话被标记为正在运行。
这是代码:
#!/usr/bin/env python2.7
import sys
import os
import time
import objc
import QTKit
import AppKit
from Foundation import NSObject
from Foundation import NSTimer
from PyObjCTools import AppHelper
objc.setVerbose(True)
class CaptureDelegate(NSObject):
def captureOutput_didOutputVideoFrame_withSampleBuffer_fromConnection_(self, captureOutput,
videoFrame, sampleBuffer,
connection):
# This should get called for every captured frame
print "Got a frame: %s" % videoFrame
class QuitClass(NSObject):
def quitMainLoop_(self, aTimer):
# Just stop the main loop.
print "Quitting main loop."
AppHelper.stopEventLoop()
def startImageCapture():
error = None
# Create a QT Capture session
session = QTKit.QTCaptureSession.alloc().init()
# Find iSight device and open it
dev = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_(QTKit.QTMediaTypeVideo)
print "Device: %s" % dev
if not dev.open_(error):
print "Couldn't open capture device."
return
# Create an input instance with the device we found and add to session
input = QTKit.QTCaptureDeviceInput.alloc().initWithDevice_(dev)
if not session.addInput_error_(input, error):
print "Couldn't add input device."
return
# Create an output instance with a delegate for callbacks and add to session
output = QTKit.QTCaptureDecompressedVideoOutput.alloc().init()
delegate = CaptureDelegate.alloc().init()
output.setDelegate_(delegate)
if not session.addOutput_error_(output, error):
print "Failed to add output delegate."
return
# Start the capture
print "Initiating capture..."
session.startRunning()
def main():
# Open camera and start capturing frames
startImageCapture()
# Setup a timer to quit in 10 seconds (hack for now)
quitInst = QuitClass.alloc().init()
NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(10.0,
quitInst,
'quitMainLoop:',
None,
False)
# Start Cocoa's main event loop
AppHelper.runConsoleEventLoop(installInterrupt=True)
print "After event loop"
if __name__ == "__main__":
main()
感谢您的任何帮助,您可以提供!