海康相機
優點:不用sdk直接網絡獲取
缺點:速度有1-2秒的延遲
使用型號
1280*680分辨路
#include <iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
//1.從攝像頭讀入視頻
//VideoCapture cap(0);
VideoCapture cap("rtsp://admin:fhy145145@192.168.1.62/Streaming/Channels/2"); //1 主碼流 1 1280*680 2 次碼流620*480
if (!cap.isOpened())
{
return 0;
}
Mat cam;
cap >> cam;//獲取當前幀圖像
cout << "Im.rows = " << cam.rows << endl;
cout << "Im.cols = " << cam.cols << endl;
//cout << "視頻寬度=" << width << endl;
//cout << "視頻高度=" << height << endl;
//2.循環顯示每一幀
while (1)
{
cap >> cam;//獲取當前幀圖像
if (!cam.empty())//如果某幀為空則退出循環
{
namedWindow("相機", 0);
imshow("相機", cam);//顯示當前幀圖像
waitKey(30);//延時30秒
}
}
return 0;
}
注: admin和12345分別是ip camera的用戶名和密碼,在瀏覽器上第一次登錄攝像頭的時候會進行設置;
192.168.1.64是攝像頭的默認IP,在瀏覽器中輸入即可進入登錄頁面(如下);
Channels/1和Channels/2分別對應主碼流和子碼流地址,兩者的分辨率不同。IP攝像頭無法通過opencv調節分辨率,只能在海康的監控界面的配置進行設置(如下)。
3. 攝像頭校准(calibration)(optional)
這個配置有很多,而且官方提供的校准文檔很詳細(戳這里),就不具體細講了。需要python版本的代碼的話可以直接fork這里;如果是c++版本的話可以參考這里
python
相機
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import cv2
import os
font = cv2.FONT_HERSHEY_SIMPLEX
#url='rtsp://admin:fhy145145@192.168.1.62/Streaming/Channels/1' #海康
url = 'http://192.168.1.89/webcapture.jpg?command=snap&channel=1' #雄邁
#url='rtsp://192.168.1.89:554/user=admin&password=&channel=1&stream=0.sdp?'
cam = cv2.VideoCapture(url)
cam.set(3, 640) # set video width
cam.set(4, 480) # set video height
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# For each person, enter one numeric face id
face_id = input('\n 請輸入用戶數字編號(只能是數字): ')
print("\n [INFO] Initializing face capture. Look the camera and wait ...")
# Initialize individual sampling face countdsa
count = 0
while(True):
ret, img = cam.read()
cv2.putText(img, str(count), (5,80), font, 1, (255,255,255), 2)
# cv2.putText(img, str("change face!"), (5,40), font, 1, (255,255,255), 2)
# img = cv2.flip(img, -1) # flip video image vertically
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2) #
cv2.putText(img, str("Perss s to save face!"), (5,40), font, 1, (255,255,255), 2)
# cv2.imshow('image', img)
k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
if k == ord('s'):
count += 1
cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
break
elif k == 27:
break
cv2.imshow('image', img)
k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
if k == 27:
break
elif count >= 30: # Take 30 face sample and stop video
break
# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
