Saturday, 12 October 2013

Kivy python script for capturing displaying webcam

Kivy is very cool. It allows you to make graphical user interfaces for computers, tablets and smart phones ... in Python. Which is great for people like me. And you, I'm sure. And it's open source, of course.

Today was my first foray into programming using Kivy. Here was my first 'app'. It's not very sophisticated, but I find Kivy's documentation rather impenetrable and frustratingly lacking in examples. Therefore I hope more people like me post their code and projects on blogs.

Right, it detects and displays your webcam on the screen, draws a little button in the bottom. When you press that button it takes a screengrab and writes it to an image file. Voila! Maximise the window before you take a screen shot for best effects.

import kivy
kivy.require('1.7.2')
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.camera import Camera
from kivy.uix.button import Button
from kivy.core.window import Window
class CamApp(App):
# Function to take a screenshot
def screengrab(self,*largs):
outname = self.fileprefix+'_%(counter)04d.png'
Window.screenshot(name=outname)
def build(self):
# create a floating layout as base
camlayout = FloatLayout(size=(600, 600))
cam = Camera() #Get the camera
cam=Camera(resolution=(1024,1024), size=(300,300))
cam.play=True #Start the camera
camlayout.add_widget(cam)
button=Button(text='Take Picture',size_hint=(0.12,0.12))
button.bind(on_press=self.screengrab)
camlayout.add_widget(button) #Add button to Camera Layout
self.fileprefix = 'snap'
return camlayout
if __name__ == '__main__':
CamApp().run()


2 comments:

Unknown said...

This would take a capture from the whole App window. Not just what the camera see.

Unknown said...

Hi so basically this program gives me an error when working saying that the resolution is not supported. If I remove resolution the webcam does not show up. Is there any way I can solve the problem. I am using Windows 10. Thanks