天天看點

csi python 攝像頭 樹莓派_樹莓派之攝像頭和人臉識别

安裝好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

以下運作的示例:

[email protected]:~ $ 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'.

csi python 攝像頭 樹莓派_樹莓派之攝像頭和人臉識别

使用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")

拍到的照片如下:

csi python 攝像頭 樹莓派_樹莓派之攝像頭和人臉識别

通過以上程式的運作,框出了臉所在區域,

csi python 攝像頭 樹莓派_樹莓派之攝像頭和人臉識别

并将這些部分區域截取出來,存成小檔案。

csi python 攝像頭 樹莓派_樹莓派之攝像頭和人臉識别