Python+OpenCVでWEBカメラ撮影

Python2.7+OpenCV2.2+TkinterでWebカメラで撮影するサンプル・プログラムを書いてみた。
拍子抜けするほど簡単なのに驚いてしまった。

(注)TkinterとOpenCVは2012-02-05「PythonのtkinterとOpenCVを繋ごう」の改造版

#!/usr/local/bin/python
# coding: cp932
################################################################################
# hi-cheese.py
# Description:  Webカメラで撮影
# Author:       shozo fukuda
# Date:         Mon Feb 20 23:20:02 2012
# Application:  Python version 2.7
################################################################################

#<IMPORT>
import Tkinter as Tk
import tkFileDialog as FileDlg
from cv import *

#<CLASS>########################################################################
# Description:  Webカメラ
# Dependencies: マウスの左クリックで撮影、右クリックで保存
################################################################################
class WebCam(Tk.Label):
  def takepicture(self, event=None):
    self.img = QueryFrame(self.cap)
    self.pho = Tk.PhotoImage(data=self.img.toppm())
    self.configure(image=self.pho)
  
  def savepicture(self, event):
    filename = FileDlg.asksaveasfilename(
      defaultextension='jpg',
      filetypes=[('jpeg files', '*.jpg'),('all files', '*.*')],
      initialfile='image'
    )
    if filename:
      SaveImage(filename.encode('cp932'), self.img)

  def __init__(self, autoloop=True, master=None):
    Tk.Label.__init__(self, master)
    self.master.title(u"ハイ!ち〜ず")
    self.pack()
    self.bind_all('<1>', self.takepicture)
    self.bind_all('<3>', self.savepicture)

    self.cap = CaptureFromCAM(-1)
    self.takepicture()
    if autoloop: self.mainloop()

#<MAIN>#########################################################################
# Function:     メインルーチン
################################################################################
app = WebCam()
  
# hi-cheese.py