>  기사  >  백엔드 개발  >  카메라 해상도와 다양한 매개변수를 설정하는 python opencv 메소드_python

카메라 해상도와 다양한 매개변수를 설정하는 python opencv 메소드_python

不言
不言원래의
2018-05-18 14:40:309448검색

다음은 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)을 사용하여 수정할 수 있습니다. 예를 들어, 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(&#39;%s&#39;%motor_value)
x=[]
else:
if i==fps:
face.neck_puber.publish(&#39;1500&#39;)
i=1
else:
i +=1
print (U&#39;未检测到人脸&#39;)
if cv2.waitKey(1) & 0xFF == ord(&#39;q&#39;):
break
except Exception,e:
print e
cap.release()
cv2.destroyAllWindows()

관련 추천:

python opencv 이미지 크기 변환 방법

Python-OpenCV 기본 연산 방법에 대한 자세한 설명_python

opencv를 사용하여 이미지를 읽는 Python 자세한 예



위 내용은 카메라 해상도와 다양한 매개변수를 설정하는 python opencv 메소드_python의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.