天天看點

python opencv設定攝像頭分辨率以及各個參數

1,為了擷取視訊,你應該建立一個 VideoCapture 對象。他的參數可以是裝置的索引号,或者是一個視訊檔案。裝置索引号就是在指定要使用的攝像頭。一般的筆記本電腦都有内置攝像頭。是以參數就是 0。你可以通過設定成 1 或者其他的來選擇别的攝像頭。之後,你就可以一幀一幀的捕獲視訊了。但是最後,别忘了停止捕獲視訊。使用 ls /dev/video*指令可以檢視攝像頭裝置

2,cap.read() 傳回一個布爾值(True/False)。如果幀讀取的是正确的,就是 True。是以最後你可以通過檢查他的傳回值來檢視視訊檔案是否已經到了結尾。有時 cap 可能不能成功的初始化攝像頭裝置。這種情況下上面的代碼會報錯。你可以使用 cap.isOpened(),來檢查是否成功初始化了。如果傳回值是True,那就沒有問題。否則就要使用函數 cap.open()。你可以使用函數 cap.get(propId) 來獲得視訊的一些參數資訊。這裡propId 可以是 0 到 18 之間的任何整數。每一個數代表視訊的一個屬性,見表其中的一些值可以使用cap.set(propId,value) 來修改,value 就是

你想要設定成的新值。例如,我可以使用 cap.get(3) 和 cap.get(4) 來檢視每一幀的寬和高。預設情況下得到的值是 640X480。但是我可以使用 ret=cap.set(3,320)和 ret=cap.set(4,240) 來把寬和高改成 320X240。

CV_CAP_PROP_POS_MSEC Current position of the video file

in milliseconds.

• CV_CAP_PROP_POS_FRAMES 0-based index of the frame to

be decoded/captured next.

• CV_CAP_PROP_POS_AVI_RATIO Relative position of the

video file: 0 - start of the film, 1 - end of the film.

• CV_CAP_PROP_FRAME_WIDTH Width of the frames in the

video stream.

• CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the

video stream.

• CV_CAP_PROP_FPS Frame rate.

• CV_CAP_PROP_FOURCC 4-character code of codec.

• CV_CAP_PROP_FRAME_COUNT Number of frames in the

video file.

• CV_CAP_PROP_FORMAT Format of the Mat objects returned

by retrieve() .

• CV_CAP_PROP_MODE Backend-specific value indicating the

current capture mode.

• CV_CAP_PROP_BRIGHTNESS Brightness of the image (only

for cameras).

• CV_CAP_PROP_CONTRAST Contrast of the image (only for

cameras).

• CV_CAP_PROP_SATURATION Saturation of the image (only

for cameras).

• CV_CAP_PROP_HUE Hue of the image (only for cameras).

• CV_CAP_PROP_GAIN Gain of the image (only for cameras).

• CV_CAP_PROP_EXPOSURE Exposure (only for cameras).

• CV_CAP_PROP_CONVERT_RGB Boolean flags

whether images should be converted to RGB.

indicating

• CV_CAP_PROP_WHITE_BALANCE Currently unsupported

• CV_CAP_PROP_RECTIFICATION Rectification flag for stereo

cameras (note: only supported by DC1394 v 2.x backend cur-

rently)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy
from hlf_module import hlf_define
from std_msgs.msg import String
import matplotlib.pyplot as plot
import xml.dom.minidom
import pylab
import rospy
import time

cap = cv2.VideoCapture(0)
cap.set(3,640) #設定分辨率
cap.set(4,480)
fps =cap.get(cv2.CAP_PROP_FPS) #擷取視訊幀數
face_casade = cv2.CascadeClassifier('/opt/ros/kinetic/share/OpenCV-3.2.0-dev/haarcascades/haarcascade_frontalface_default.xml')
Node_name='neck'
#print cap.isOpened()
class Detect_face():
def __init__(self):
'''定義節點Node_name(全局變量,而非具體名稱)'''
self.err_pub=hlf_define.err_publisher()#錯誤消息釋出者
rospy.init_node(Node_name,anonymous=True)
self.neck_puber=rospy.Publisher(hlf_define.TOPIC_ACTION_NECK,String,queue_size=10)
time.sleep(0.5)
def head_motor_value(self):#解析xml檔案 擷取舵機的範圍值
dom = xml.dom.minidom.parse('/home/sb/catkin_ws/src/hlf_robot/scripts/hlf_action/head_value.xml')
#得到文檔元素對象
root = dom.documentElement

itemlist = root.getElementsByTagName('login')
item = itemlist[0]
max_value=item.getAttribute("max")
min_value=item.getAttribute("min")

return max_value,min_value

def detect_face(self):
# get a frame
#frame=cv2.imread('/home/sb/桌面/timg.jpeg')
ret, frame = cap.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)#轉成灰階圖
#frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
# show a frame
cv2.imshow("capture", gray)
faces = face_casade.detectMultiScale(gray,1.2,5) #檢測人臉
#print len(faces)
if len(faces)>0:#判斷是否檢測到人臉
result = ()
max_face = 0
value_x=0
for (x,y,w,h) in faces:
if (w*h > max_face): #檢測最大人臉
max_face = w*h
result = (x,y,w,h)

# max_face.append(width*height)
x=result[0]
w=result[2]
z=value_x=value_x+x+w/2
return z
else:
return 1

if __name__=='__main__':
face=Detect_face()
motor_max,motor_min= face.head_motor_value()
x=[]
i=1
while True:
try:
z=face.detect_face()
if z != 1:
x.append(z)
if len(x)>(fps-1):
true_x = int(sum(x)/30)
if(true_x>319):
motor_value=int(1500+(int(motor_max)-1500)*(true_x-319)/320)#轉換成舵機值 頭部向左轉
face.neck_puber.publish('%s'%motor_value)
elif (true_x<319):
motor_value=int(1500-(1500-int(motor_min))*(319-true_x)/320)
face.neck_puber.publish('%s'%motor_value)
x=[]
else:
if i==fps:
face.neck_puber.publish('1500')
i=1
else:
i +=1
print (U'未檢測到人臉')
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except Exception,e:
print e
cap.release()
cv2.destroyAllWindows()
           

繼續閱讀