安装好Python与树莓派外置硬件GPIO库文件
sudo apt-get install python-rpi.gpio
在python中使用GPIO示例:
import RPi.GPIO as GPIO
#### gpio init
GPIO.setmode(GPIO.BCM)
GPIO.setup(7, GPIO.OUT) #LED2
GPIO.setup(8, GPIO.OUT) #LED1
GPIO.output(7, GPIO.LOW) #LED2 ON
GPIO.output(8, GPIO.HIGH)#LED1 OFF
fswebcam,这是一款小型摄像头程序,可以直接通过Raspbian的仓库来安装,
sudo apt-get install fswebcam
fswebcam --help
以下运行的示例:
pi@raspberrypi:~ $ fswebcam --no-banner --device /dev/video0 -r 1600x1200 b.jpg
--- Opening /dev/video0...
Trying source module v4l2...
/dev/video0 opened.
No input was specified, using the first.
--- Capturing frame...
Captured frame in 0.00 seconds.
--- Processing captured image...
Disabling banner.
Writing JPEG image to 'b.jpg'.
使用opencv自带的VideoCapture()函数定义摄像头对象,其参数0表示第一个摄像头,保存一张照片:
#-*- coding=utf-8 -*-
import cv2
import numpy as np
import time
cap = cv2.VideoCapture(1)
ret,frame = cap.read()
#cv2.imshow('frame',frame)#一个窗口用以显示原视频
filename = "/home/pi/" + time.strftime('%Y%m%d-%H%M%S') + ".jpg"
cv2.imwrite(filename, frame)
cap.release()
cv2.destroyAllWindows()
以下实例通过USB摄像头拍摄一张图片,并通过载入特征文件对图片进行人脸识别,取出对应的人脸部分并保存为小图。
特征文件可以通过在命令行中用find命令来查找:
sudo find / -iname "*haarcascades*" > /home/pi/opencv_find.txt
完整的代码如下:
#-*- coding=utf-8 -*-
import os
from PIL import Image, ImageDraw
import cv2.cv as cv
import cv2
#OPCV_PATH = "/opt/Wolfram/WolframEngine/11.2/SystemFiles"
def detect_object(image):
'''检测图片,获取人脸在图片中的坐标'''
grayscale = cv.CreateImage((image.width, image.height), 8, 1)
cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)
#cascade = cv.Load(OPCV_PATH+"/Data/haarcascades/frontalface.xml")
cascade = cv.Load("/opt/Wolfram/WolframEngine/11.2/SystemFiles/Data/Haarcascades/frontalface.xml")
rect = cv.HaarDetectObjects(grayscale, cascade, cv.CreateMemStorage(), 1.1, 2,
cv.CV_HAAR_DO_CANNY_PRUNING, (20,20))
result = []
for r in rect:
result.append((r[0][0], r[0][1], r[0][0]+r[0][2], r[0][1]+r[0][3]))
return result
def process(infile):
'''在原图上框出头像并且截取每个头像到单独文件夹'''
image = cv.LoadImage(infile);
if image:
faces = detect_object(image)
im = Image.open(infile)
path = os.path.abspath(infile)
save_path = os.path.splitext(path)[0]+"_face"
#save_path = "/home/pi" + "_face"
try:
os.mkdir(save_path)
except:
pass
if faces:
draw = ImageDraw.Draw(im)
count = 0
for f in faces:
count += 1
draw.rectangle(f, outline=(255, 0, 0))
a = im.crop(f)
file_name = os.path.join(save_path,str(count)+".jpg")
# print file_name
a.save(file_name)
drow_save_path = os.path.join(save_path,"out.jpg")
im.save(drow_save_path, "JPEG", quality=80)
else:
print "Error: cannot detect faces on %s" % infile
if __name__ == "__main__":
os.system("fswebcam --no-banner --device /dev/video0 -r 1600x1200 b.jpg")
process("b.jpg")
拍到的照片如下:
通过以上程序的运行,框出了脸所在区域,
并将这些部分区域截取出来,存成小文件。