樹莓派OpenCV系列教程2:攝像頭的基本使用

PS:本章將介紹計算機視覺中最核心傳感器-攝像頭的基本使用,主要講解了CSI攝像頭,USB攝像頭,網(wǎng)絡(luò)攝像頭的基本使用。

1 CSI攝像頭
首先將講解CSI攝像頭的使用:

1.1 picamera
樹莓派自帶的攝像頭為CSI攝像頭,在樹莓派平臺中,發(fā)行版的Raspbian默認安裝了樹莓派平臺的picamera:
相關(guān)官方文檔鏈接:https://picamera.readthedocs.io/en/release-1.13/index.html
執(zhí)行該腳本將錄制一段10秒的視頻到本地:
import picamera
camera = picamera.PiCamera()
camera.resolution = (640, 480)
camera.start_recording('my_video.h264')
camera.wait_recording(10)
camera.stop_recording()
但由于picamera輸出的數(shù)據(jù)是RGB格式的,需要通過Numpy轉(zhuǎn)換為BGR格式,代碼如下:
import time
import picamera
import numpy as np
import CV2
with picamera.PiCamera() as camera:
? ? camera.resolution = (320, 240)
? ? camera.framerate = 24
? ? time.sleep(2)
? ? image = np.empty((240 * 320 * 3,), dtype=np.uint8)
? ? # save as bgr format for OpenCV
? ? camera.capture(image, 'bgr')
? ? image = image.reshape((240, 320, 3))
? ? CV2.imshow("img", image)
? ? if(CV2.waitKey(0) == ord('q')):
? ? ? ? exit(0)
當(dāng)然,picamera 也提供了PIRGBArray對象,用來保存RGB 圖像數(shù)據(jù),下面將在capture_continuous函數(shù)中,不斷地把RGB轉(zhuǎn)換成BGR圖像,供OpenCV顯示,以形成視頻流。
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import CV2
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera)
# allow the camera to warmup
time.sleep(0.1)
# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
? ? image = frame.array
? ? # show the frame
? ? CV2.imshow("Frame", image)
? ? # prepare for net stream
? ? rawCapture.truncate(0)
? ? if(CV2.waitKey(1) == ord('q')):
? ? ? ? CV2.destroyAllWindows()
? ? ? ? break;
但由于picamera為樹莓派或兼容樹莓派平臺專用的庫,且僅能供樹莓派使用,下面將介紹更為通用的使用方法。
1.2 V4L2
目前,CSI攝像頭可通過picamera等庫進行調(diào)用,但在Raspbian系統(tǒng)中,并不屬于一個video設(shè)備而存在,若想將CSI攝像頭作為一個視頻設(shè)備文件使用,則要開啟V4L2(Video for Linux 2)模塊以開啟:
開啟方法如下:
sudo vim /etc/modules
在末尾添加一行:
bcm2835-v4l2
此時,CSI攝像頭便成為了一個video設(shè)備,此時在終端執(zhí)行:
ls -ltrh /dev/video*
便可查看到video設(shè)備,其中video0便是CSI攝像頭:

該video設(shè)備可同時供Python與C++調(diào)用,具體使用請參考《樹莓派OpenCV系列教程1:開發(fā)環(huán)境搭建》的例程。
2 USB攝像頭
樹莓派除了支持CSI攝像頭外,同樣也支持USB攝像頭:

若采用USB攝像頭,若攝像頭本身免驅(qū),接入樹莓派后,將直接識別的video設(shè)備,在/dev下可找到對應(yīng)的video設(shè)備,在中斷,輸入命令:
ls -ltrh /dev/video*
即可查詢到新接入的video設(shè)備。
但使用Python,C++使用攝像頭,區(qū)分不同的攝像頭時:
c++:
VideoCapture cap(0);
python:
cap = CV2.VideoCapture(0)
傳入?yún)?shù)0代表使用CSI攝像頭,傳入其它參數(shù)代表使用其它video序號對應(yīng)的USB攝像頭。
具體使用請參考《1.OpenCV開發(fā)環(huán)境搭建》的例程。
3 網(wǎng)絡(luò)攝像頭
除了使用CSI攝像頭,USB攝像頭外,還可以將手機變成一個IP攝像頭,具體方法如下:
在手機應(yīng)用市場中,搜索這款名為IP攝像頭的APP,圖標如下:

安裝好后,連接wifi,確保樹莓派和手機處在同一局域網(wǎng)內(nèi),手機打開IP攝像頭軟件,同時點擊打開IP攝像頭服務(wù)器,即可將手機變成一個IP攝像頭。如下圖所示:

此時,在瀏覽器中打開該IP地址,輸入用戶名:admin,密碼:admin,即可瀏覽攝像頭畫面:

此時說明手機成為了一個IP攝像頭,此攝像頭可供OpenCV調(diào)用。
OpenCV調(diào)用IP攝像頭的源程序如下:
3.1 Python3
#!/usr/bin/env python
'''
Waveshare OpenCV Tutorial
01_IP_Camera.py
A demo to show whether The OpenCV and IP camera is well installed
'''
import numpy as np
import CV2
def main():
? ? print("OpenCV Version:{}".format(CV2.__version__))
? ? # 0: use CSI camera,1:use USB camera
? ? ip_camera_url = 'http://admin:admin@192.168.10.215:8081'
? ? cap = CV2.VideoCapture(ip_camera_url)
? ? if(not cap.isOpened()):
? ? ? ? print("can't open this camera")
? ? while(True):
? ? ? ? ret, FrameImage = cap.read()
? ? ? ? if ret == True:
? ? ? ? ? ? CV2.imshow('Camera Capture',FrameImage)
? ? ? ? ? ? #Press Q to quit
? ? ? ? ? ? if (CV2.waitKey(1)) == ord('q'):
? ? ? ? ? ? ? ? cap.release()
? ? ? ? ? ? ? ? break
? ? ? ? else:
? ? ? ? ? ? break
if __name__ == '__main__':
? ? print(__doc__)
? ? main()
? ? # Release resource
? ? CV2.destroyAllWindows()
運行效果如下圖所示:

3.2 C++
相應(yīng)地,C++程序讀取網(wǎng)絡(luò)攝像頭的程序如下:
#include<iostream>
#include<openCV2/opencv.hpp>
#include<openCV2/highgui/highgui.hpp>
#include<openCV2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main()
{
? ? cout << "Waveshare OpenCV Tutorial"<< endl;
? ? cout << "00_Test_OpenCV"<cout << "A demo to show whether The OpenCV and IP camera is well installed" <cout << endl;
? ? cout << "OpenCV Version:" << CV_VERSION << endl;
? ? const string ip_camera_url = "http://admin:admin@192.168.10.215:8081";
? ? VideoCapture cap(ip_camera_url);
? ? if(!cap.isOpened())
? ? {
? ? ? ? cout<<"can't open this camera"<return -1;
? ? }? ??
? ? Mat FrameImage;
? ? while(1)
? ? {
? ? ? ? cap>>FrameImage;
? ? ? ? imshow("Camera Capture",FrameImage);
? ? ? ? //Press Q to quit
? ? ? ? if(char(waitKey(1)) == 'q')
? ? ? ? {
? ? ? ? ? ? break;
? ? ? ? }
? ? }
? ? return 0;
}
運行效果如下圖所示:

樹莓派OpenCV系列教程2:攝像頭的基本使用的評論 (共 條)
