樹莓派相機︰ PiCamera 《一》

若問學習一個程式庫可有善法的耶?唯有多讀幾遍介面文件,嘗試使用而已乎!  PiCamera 已是少見手冊完備,範例周全之程式庫的哩,而且官方版之 Raspbian 預設安裝矣,直須從

2. Getting Started

Warning

Make sure your Pi is off while installing the camera module. Although it is possible to install the camera while the Pi is on, this isn’t good practice (if the camera is active when removed, it’s possible to damage it).

Connect your camera module to the CSI port on your Raspberry Pi; this is the long thin port adjacent to the HDMI socket. Gently lift the collar on top of the CSI port (if it comes off, don’t worry, you can push it back in but try to be more gentle in future!). Slide the ribbon cable of the camera module into the port with the blue side facing the Ethernet port (or where the Ethernet port would be if you’ve got a model A/A+).

Once the cable is seated in the port, press the collar back down to lock the cable in place. If done properly you should be able to easily lift the Pi by the camera’s cable without it falling out. The following illustrations show a well-seated camera cable with the correct orientation:

_images/good_connection.jpg

Make sure the camera module isn’t sat on anything conductive (e.g. the Pi’s USB ports or its GPIO pins). Now, apply power to your Pi. Once booted, start the Raspberry Pi Configuration utility and enable the camera module:

_images/enable_camera.png

You will need to reboot after doing this (but this is one-time setup so you won’t need to do it again unless you re-install your operating system or switch SD cards). Once rebooted, start a terminal and try the following command:

raspistill -o image.jpg

If everything is working correctly, the camera should start, a preview from the camera should appear on the display and, after a 5 second delay it should capture an image (storing it as image.jpg) before shutting down the camera. Proceed to the Basic Recipes.

If something else happens, read any error message displayed and try any recommendations suggested by such messages. If your Pi reboots as soon as you run this command, your power supply is insufficient for running your Pi plus the camera module (and whatever other peripherals you have attached).

……

往下讀就好︰

3. Basic Recipes

The following recipes should be reasonably accessible to Python programmers of all skill levels. Please feel free to suggest enhancements or additional recipes.

3.1. Capturing to a file

Capturing an image to a file is as simple as specifying the name of the file as the output of whatever capture() method you require:

from time import sleep
from picamera import PiCamera

camera = PiCamera()
camera.resolution = (1024, 768)
camera.start_preview()
# Camera warm-up time
sleep(2)
camera.capture('foo.jpg')

 

Note that files opened by picamera (as in the case above) will be flushed and closed so that when the capture method returns, the data should be accessible to other processes.

3.2. Capturing to a stream

Capturing an image to a file-like object (a socket(), a io.BytesIO stream, an existing open file object, etc.) is as simple as specifying that object as the output of whatever capture() method you’re using:

from io import BytesIO
from time import sleep
from picamera import PiCamera

# Create an in-memory stream
my_stream = BytesIO()
camera = PiCamera()
camera.start_preview()
# Camera warm-up time
sleep(2)
camera.capture(my_stream, 'jpeg')

Note that the format is explicitly specified in the case above. The BytesIO object has no filename, so the camera can’t automatically figure out what format to use.

 

然而好學者常會自問自答︰

5. Frequently Asked Questions (FAQ)

5.1. AttributeError: ‘module’ object has no attribute ‘PiCamera’

You’ve named your script picamera.py (or you’ve named some other script picamera.py. If you name a script after a system or third-party package you will break imports for that system or third-party package. Delete or rename that script (and any associated .pyc files), and try again.

5.2. Can I put the preview in a window?

No. The camera module’s preview system is quite crude: it simply tells the GPU to overlay the preview on the Pi’s video output. The preview has no knowledge (or interaction with) the X-Windows environment (incidentally, this is why the preview works quite happily from the command line, even without anyone logged in).

That said, the preview area can be resized and repositioned via the window attribute of the preview object. If your program can respond to window repositioning and sizing events you can “cheat” and position the preview within the borders of the target window. However, there’s currently no way to allow anything to appear on top of the preview so this is an imperfect solution at best.

 

努力貫通已學程式庫的吧︰

Python Imaging Library (PIL)

The Python Imaging Library (PIL) adds image processing capabilities to your Python interpreter. This library supports many file formats, and provides powerful image processing and graphics capabilities.

Status

The current free version is PIL 1.1.7. This release supports Python 1.5.2 and newer, including 2.5 and 2.6. A version for 3.X will be released later.

……

或應改為

python-pillow/Pillow

About

Goals

The fork author’s goal is to foster and support active development of PIL through:

License

Like PIL, Pillow is licensed under the MIT-like open source PIL Software License:

Software License

The Python Imaging Library (PIL) is

    Copyright © 1997-2011 by Secret Labs AB
    Copyright © 1995-2011 by Fredrik Lundh

By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Why a fork?

PIL is not setuptools compatible. Please see this Image-SIG post for a more detailed explanation. Also, PIL’s current bi-yearly (or greater) release schedule is too infrequent to accommodate the large number and frequency of issues reported.

What about PIL?

Note

Prior to Pillow 2.0.0, very few image code changes were made. Pillow 2.0.0 added Python 3 support and includes many bug fixes from many contributors.

As more time passes since the last PIL release, the likelihood of a new PIL release decreases. However, we’ve yet to hear an official “PIL is dead” announcement. So if you still want to support PIL, please report issues here first, then open corresponding Pillow tickets here.

Please provide a link to the first ticket so we can track the issue(s) upstream.

───《W!o+ 的《小伶鼬工坊演義》︰神經網絡【MNIST】一

 

因而能學而時習之︰

Tutorial

Using the Image class

The most important class in the Python Imaging Library is the Image class, defined in the module with the same name. You can create instances of this class in several ways; either by loading images from files, processing other images, or creating images from scratch.

To load an image from a file, use the open() function in the Image module:

>>> from PIL import Image
>>> im = Image.open("lena.ppm")

If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:

>>> from __future__ import print_function
>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB

The format attribute identifies the source of an image. If the image was not read from a file, it is set to None. The size attribute is a 2-tuple containing width and height (in pixels). The mode attribute defines the number and names of the bands in the image, and also the pixel type and depth. Common modes are “L” (luminance) for greyscale images, “RGB” for true color images, and “CMYK” for pre-press images.

If the file cannot be opened, an IOError exception is raised.

Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate the image. For example, let’s display the image we just loaded:

>>> im.show()

 

 

 

 

 

 

 

 

 

 

 

樹莓派相機︰ RaspiCAM 之軟件《三》

講到 RaspiCAM 之應用軟件程式庫,焉能不提及大名鼎鼎的

 OpenCV is released under a BSD license and hence it’s free for both academic and commercial use. It has C++, C, Python and Java interfaces and supports Windows, Linux, Mac OS, iOS and Android. OpenCV was designed for computational efficiency and with a strong focus on real-time applications. Written in optimized C/C++, the library can take advantage of multi-core processing. Enabled with OpenCL, it can take advantage of the hardware acceleration of the underlying heterogeneous compute platform. Adopted all around the world, OpenCV has more than 47 thousand people of user community and estimated number of downloads exceeding 9 million. Usage ranges from interactive art, to mines inspection, stitching maps on the web or through advanced robotics.

ABOUT

OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.

The library has more than 2500 optimized algorithms, which includes a comprehensive set of both classic and state-of-the-art computer vision and machine learning algorithms. These algorithms can be used to detect and recognize faces, identify objects, classify human actions in videos, track camera movements, track moving objects, extract 3D models of objects, produce 3D point clouds from stereo cameras, stitch images together to produce a high resolution image of an entire scene, find similar images from an image database, remove red eyes from images taken using flash, follow eye movements, recognize scenery and establish markers to overlay it with augmented reality, etc. OpenCV has more than 47 thousand people of user community and estimated number of downloads exceeding 7 million. The library is used extensively in companies, research groups and by governmental bodies.

Along with well-established companies like Google, Yahoo, Microsoft, Intel, IBM, Sony, Honda, Toyota that employ the library, there are many startups such as Applied Minds, VideoSurf, and Zeitera, that make extensive use of OpenCV. OpenCV’s deployed uses span the range from stitching streetview images together, detecting intrusions in surveillance video in Israel, monitoring mine equipment in China, helping robots navigate and pick up objects at Willow Garage, detection of swimming pool drowning accidents in Europe, running interactive art in Spain and New York, checking runways for debris in Turkey, inspecting labels on products in factories around the world on to rapid face detection in Japan.

It has C++, C, Python, Java and MATLAB interfaces and supports Windows, Linux, Android and Mac OS. OpenCV leans mostly towards real-time vision applications and takes advantage of MMX and SSE instructions when available. A full-featured CUDA and OpenCL interfaces are being actively developed right now. There are over 500 algorithms and about 10 times as many functions that compose or support those algorithms. OpenCV is written natively in C++ and has a templated interface that works seamlessly with STL containers.

OpenCV Developers Team:

 

之前 o4l 【only for linux】老友寫過 Python 2.7 的

opencv 3 安裝

,據聞當時 Python 3.x 還有些編譯問題。由於作者偏好派生三支援萬國碼,能寫中文化程式。因此嘗試安裝最新 github 原始碼,終究皇天不負苦心人乎!

sudo apt-get install build-essential git cmake pkg-config
sudo apt-get install libtiff5-dev libjasper-dev libpng12-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libgtk2.0-dev
sudo apt-get install libatlas-base-dev gfortran
sudo apt-get install python3-dev
sudo pip-3.2 install numpy
git clone https://github.com/Itseez/opencv.git
git clone https://github.com/Itseez/opencv_contrib.git
cd opencv
mkdir build
build/
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules -D BUILD_EXAMPLES=ON ..
make -j4
sudo make install
sudo ldconfig
cd
ln -s /usr/local/lib/python3.4/dist-packages/cv2.cpython-34m.so cv2.so

 

將要如何驗證安裝的呢?一時想起了曾經讀過之癹文 POST︰

Install OpenCV 3.1 Python/C++ on Raspbian Jessie

。於是依樣畫葫蘆一番耶!

pi@raspberrypi:~ python3 Python 3.4.2 (default, Oct 19 2014, 13:31:11)  [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> print (cv2.__version__) 3.1.0-dev >>>  </pre>   <pre class="lang:python decode:true ">mkdir test cd test nano 樹莓派相機測試.py  pi@raspberrypi:~/test more 樹莓派相機測試.py 
import numpy as np
import cv2
擷取 = cv2.VideoCapture(0)
if 擷取.isOpened() == False:
    print('錯誤: 不能打開相機')
else:
    print('開始擷取,按任意鍵結束')
    cv2.namedWindow('擷取視窗');
    while( 擷取.isOpened() ):
        傳回值,畫面 = 擷取.read()
        if 傳回值==False:
            print('錯誤: 不能擷取畫面')
            break;
 
        cv2.imshow('擷取視窗',畫面)
        if cv2.waitKey(1) >= 0:
           break
    print('關閉相機')
 
擷取.release()
cv2.destroyAllWindows()
print('再見')
pi@raspberrypi:~/test python3 樹莓派相機測試.py  開始擷取,按任意鍵結束 關閉相機 再見 pi@raspberrypi:~/test

 

%e6%93%b7%e5%8f%96%e8%a6%96%e7%aa%97

 

 

 

 

 

 

 

 

 

 

樹莓派相機︰ RaspiCAM 之軟件《二》

道德經 (王弼本)

三十三章

知人者智,自知者明。知人者,智而已矣,未若自知者超智之上也。 勝人者有力,自勝者強。勝人者,有力而已矣,未若自勝者無物以損其力,用其智於人,未若用其智於己也。用其力於人,未若用其力於己也。明用於己,則物無避焉,力用於己,則物無改焉。 知足者富。知足自不失,故富也。 強行者有志 。勤能行之,其志必獲,故曰強行者有志矣。 不失其所者久。以明自察,量力而行,不失其所,必獲久長矣。 死而不亡者壽。雖死而以為生之道不亡,乃得全其壽,身沒而道猶存,況身存而道不卒乎。

 

史實與小說不同,其人其事果能全真乎?

周伯通

周伯通金朝山東寧海(今山東牟平)人,知名全真道居士

史實

王重陽始創全真道時曾受其資助。周伯通是全真道北七真馬鈺譚處端王處一郝大通孫不二同鄉。當時在寧海、文登等地傳道的王重陽先後收了丘處機、譚處端、馬鈺、王處一、郝大通為徒。1169年春(金大定九年巳丑四月),王重陽帶領馬、譚、丘、郝四弟子回到寧海,周伯通築庵請王重陽居住,名曰「金蓮堂」。不久馬鈺的妻子孫不二也在金蓮堂出家。八月,王重陽在金蓮堂成立「三教金蓮會」。隨後王重陽赴福山登州萊州等地繼續傳道,收劉處玄

金庸武俠小說裡的周伯通

金庸的《射鵰英雄傳》及《神鵰俠侶》中,周伯通被演繹為王重陽(書中為「天下五絕」之首,有「中神通」之號)的師弟,全真七子的師叔。為金庸小說中武功最絕頂的高手之一。 周伯通滿臉花影,髮鬚烏黑,雖然甚長,卻未見斑白。

生平

周伯通天性純真, 又如孩童般任意妄為,常不看場面緩急狀況下胡鬧,故有「老頑童」之稱。他不拘小節,好武成癡,當被生平未見的武功吸引時,有甘願向施功者磕頭拜師求教的舉動。(如初見歐陽鋒施展的輕功、郭靖所練的降龍十八掌、楊過獨創的黯然銷魂掌等)。

與晚輩郭靖(《射鵰英雄傳》男主角)結拜為兄弟。

天生是個樂天派,喜歡無拘無束地玩;雖未隨王重陽出家入道,卻在全真道門內深得道家養生要旨,長壽有道,逍遙自在地生活在天地之間。

武功方面,周伯通早已不下於「天下五絕」,後來因自創絕學「空明拳」、「雙手互搏」令他的武功早與「天下五絕」不相伯仲,於教授郭靖上下卷《九陰真經》時不知不覺間習得,令他武功近乎天下第一,大概已頗不下於其師兄王重陽。於《神鵰俠侶》結尾時,繼承師兄王重陽「中神通」地位得「中頑童」之號,成為了「天下五絕」之首。

 

周伯通之『空明拳』能『雙手互搏』,一心二用至忘我一人之境 ,是否為『自勝者』耶?因此說其得道家養生要旨,豈是全假呢! ! ??不講相機軟件,反倒先講起武俠,不會太無厘頭的嗎??!!祇為先提個醒, Linux 世界的

Video4Linux

Video4Linux, V4L for short, is a collection of device drivers and an API for supporting realtime video capture on Linux systems.[1] It supports many USB webcams, TV tuners, and related devices, standardizing their output so programmers can easily add video support to their applications. MythTV, tvtime and TVHeadend are typical applications that use the V4L framework.

Video4Linux was named after Video for Windows (which is sometimes abbreviated “V4W”), but is not technically related to it.[2][3]

Version 1

V4L had been introduced late into the 2.1.X development cycle of the Linux kernel. V4L1 support was dropped in kernel 2.6.38.[4]

Version 2

V4L2 is the second version of V4L. Video4Linux2 fixed some design bugs and started appearing in the 2.5.x kernels. Video4Linux2 drivers include a compatibility mode for Video4Linux1 applications, though the support can be incomplete and it is recommended to use Video4Linux1 devices in V4L2 mode. The project DVB-Wiki is now hosted on LinuxTV web site.[5]

Some programs support V4L2 through the media resource locator v4l2://.

 

就是『練域』︰

This document covers the Linux Kernel to Userspace API’s used by video and radio streaming devices, including video cameras, analog and digital TV receiver cards, AM/FM receiver cards, streaming capture and output devices, codec devices and remote controllers.

A typical media device hardware is shown at Figure 1, “Typical Media Device”.

Figure 1. Typical Media Device

linuxtv

The media infrastructure API was designed to control such devices. It is divided into five parts.

The first part covers radio, video capture and output, cameras, analog TV devices and codecs.

The second part covers the API used for digital TV and Internet reception via one of the several digital tv standards. While it is called as DVB API, in fact it covers several different video standards including DVB-T/T2, DVB-S/S2, DVB-C, ATSC, ISDB-T, ISDB-S,etc. The complete list of supported standards can be found at the section called “fe_delivery_system type”.

The third part covers the Remote Controller API.

The fourth part covers the Media Controller API.

The fifth part covers the CEC (Consumer Electronics Control) API.

It should also be noted that a media device may also have audio components, like mixers, PCM capture, PCM playback, etc, which are controlled via ALSA API.

For additional information and for the latest development code, see: https://linuxtv.org.

For discussing improvements, reporting troubles, sending new drivers, etc, please mail to: Linux Media Mailing List (LMML)..

 

苟非『忘己成癡者』莫輕入也。幸而樹莓派官方版 RaspiCAM 乃今只要

sudo modprobe bcm2835-v4l2

,就能掛載上應用軟體『相容性』滿高之 v4l2 的 linux 驅動程式。故而作者只需

sudo apt-get install luvcview

luvcview

,就可藉著『凹面鏡』,以『樹莓派之書』觀『樹莓派之書』之『實像』的哩☆

 

luvcview-c-michel-xhaard-17-8-fps_002

 

 

 

 

 

 

 

 

 

 

 

樹莓派相機︰ RaspiCAM 之軟件《一》

欲介紹 RaspiCAM 之軟件,想起了多年前的『樹莓派之書』︰

238_p_1398108695917

 

因為它有機制可以固定相機。那時還是樹莓派 B 的天下,恐怕如今或已絕版矣!然而市面上猶難見什麼方便設計出現?雖說 3B 和 B 之定位孔不同,簡單拴鎖或仍可用也。

img_2080

 

由於我們將用到

picamera

This package provides a pure Python interface to the Raspberry Pi camera module for Python 2.7 (or above) or Python 3.2 (or above).

Indices and tables

 

程式庫,特寫在之前,希望讀者能先行閱讀的了。