Sunday, April 26, 2015

Python to capture image from Raspberry Pi Camera Module

This Python 2 code run on Raspberry Pi 2 to capture image from Camera Module.


Because the preview will cover the main screen, so this example run remotely on Android tablet running Microsoft Remote Desktop Client App, login Raspberry Pi via xrdp.


myPiCam.py
import picamera
from time import sleep
import Tkinter
import time
from PIL import ImageTk, Image


def quit():
    camera.stop_preview()
    global tkTop
    tkTop.destroy()

def setBrightness(ev=None):
    global camera
    global tkScale
    camera.brightness = tkScale.get()
    
def loadJpg(file):

    JpgWin = Tkinter.Toplevel(tkTop)
    JpgWin.title('New Window')
    JpgWin.geometry('400x300')

    image = Image.open(file)
    image = image.resize((400, 300), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(image)
    panel = Tkinter.Label(JpgWin, image=img)
    panel.pack(side = "bottom", fill = "both", expand = "yes")

    JpgWin.mainloop()

def capture():
    timeStamp = time.strftime("%Y%m%d-%H%M%S")
    jpgFile='img_'+timeStamp+'.jpg'
    camera.capture(jpgFile)
    loadJpg(jpgFile)

camera = picamera.PiCamera()
camera.start_preview()
camera.brightness = 50

tkTop = Tkinter.Tk()
tkTop.wm_title("Raspberry Pi Camera - Brightness")
tkTop.geometry('400x200')

tkButtonQuit = Tkinter.Button(
    tkTop, text="Quit", command=quit)
tkButtonQuit.pack()

tkButtonCapture = Tkinter.Button(
    tkTop, text="Capture", command=capture)
tkButtonCapture.pack()

tkScale = Tkinter.Scale(
    tkTop,
    from_=0, to=100,
    length=300,
    orient=Tkinter.HORIZONTAL,
    command=setBrightness)
tkScale
tkScale.set(50)
tkScale.pack(anchor=Tkinter.CENTER)

Tkinter.mainloop()



To run the Python code on Raspberry Pi, we need to install PIL with jpg supported:

$ sudo apt-get install libjpeg8-dev

Then find libjpeg.so and create link on /usr/lib/
$ find /usr/lib -name libjpeg.so
/usr/lib/arm-linux-gnueabihf/libjpeg.so
$ sudo ln -s /usr/lib/arm-linux-gnueabihf/libjpeg.so /usr/lib/

Then install PIL and python-imaging-tk
$ sudo apt-get install python-pip
$ sudo pip install PIL


If you reported with error like this:

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DHAVE_LIBJPEG -IlibImaging -I/usr/include -I/usr/local/include -I/usr/include/python2.7 -c _imaging.c -o build/temp.linux-armv7l-2.7/_imaging.o

_imaging.c:75:20: fatal error: Python.h: No such file or directory

compilation terminated.

error: command 'gcc' failed with exit status 1
----------------------------------------

Install python-dev:
$ sudo apt-get install python-dev


$ sudo apt-get install python-imaging-tk


Updated@2015-12-13 for Jessie:
Tested on Raspberry Pi 2 running Raspbian Jessie 2015-11-21, no need install PIL, but still have to install python-imaging-tk.


No comments: