本文整理汇总了Python中cv2.VideoCapture类的典型用法代码示例。如果您正苦于以下问题:Python VideoCapture类的具体用法?Python VideoCapture怎么用?Python VideoCapture使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VideoCapture类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Camera
class Camera(object):
def get_settings(self):
if not hasattr(self, '_video_capture'):
raise Exception("Start video capture before getting settings")
settings = []
for prop in global_camera_properties:
prop_value = self._video_capture.get(prop['value'])
if prop_value >= 0:
settings.append({'name': prop['name'], 'value': prop_value})
return settings
def set_setting(self, setting, value):
if not hasattr(self, '_video_capture'):
raise Exception("Start video capture before setting a setting")
setting_id = filter(lambda x: x['name'] == setting, global_camera_properties)
if len(setting_id) == 1:
setting_id = setting_id[0]['value']
else:
raise Exception("Setting {} not available".format(setting))
self._video_capture.set(setting_id, value)
def read(self):
(retVal, image) = self._video_capture.read()
return image
def start(self):
self._video_capture = VideoCapture(0)
self.shape = self.read().shape
def stop(self):
self._video_capture.release()
示例2: start
def start():
'''
'''
#Load splash screen
splScr = splash()
found = []
#find connected cameras
for num in range(10):
cam = VideoCapture(num)
cam.open
#show progress bar 'movement' while the main program find cameras
splScr.update()
if not cam.read()[0]:
del(cam)
else:
cam.release()
found.append(num)
while gtk.events_pending():
gtk.main_iteration()
#destroy splash screen when all cameras are finded
splScr.destroy()
print 'connected cameras:', len(found)
#run main program
main_gui(found)
gtk.main()
return
示例3: FileCapture
class FileCapture():
"""
simple file capture that can auto_rewind
"""
def __init__(self,src):
self.auto_rewind = True
self.controls = None #No UVC controls available with file capture
# we initialize the actual capture based on cv2.VideoCapture
self.cap = VideoCapture(src)
timestamps_loc = os.path.join(src.rsplit(os.path.sep,1)[0],'eye_timestamps.npy')
logger.info("trying to load timestamps with video at: %s"%timestamps_loc)
try:
self.timestamps = np.load(timestamps_loc).tolist()
logger.info("loaded %s timestamps"%len(self.timestamps))
except:
logger.info("did not find timestamps")
self.timestamps = None
self._get_frame_ = self.cap.read
def get_size(self):
return self.cap.get(3),self.cap.get(4)
def set_fps(self):
pass
def get_fps(self):
return None
def read(self):
s, img =self._get_frame_()
if self.auto_rewind and not s:
self.rewind()
s, img = self._get_frame_()
return s,img
def get_frame(self):
s, img = self.read()
if self.timestamps:
timestamp = self.timestamps.pop(0)
else:
timestamp = time()
return Frame(timestamp,img)
def rewind(self):
self.cap.set(1,0) #seek to the beginning
def create_atb_bar(self,pos):
return 0,0
def kill_atb_bar(self):
pass
def close(self):
pass
示例4: Camera_Capture
class Camera_Capture():
"""
VideoCapture without uvc control using cv2.VideoCapture
"""
def __init__(self,src_id,size=(640,480),fps=None,timebase=None):
self.controls = None
self.cvId = src_id
self.name = "VideoCapture"
self.controls = None
###add cv videocapture capabilities
self.capture = VideoCapture(src_id)
self.set_size(size)
if timebase == None:
logger.debug("Capture will run with default system timebase")
self.timebase = c_double(0)
elif isinstance(timebase,c_double):
logger.debug("Capture will run with app wide adjustable timebase")
self.timebase = timebase
else:
logger.error("Invalid timebase variable type. Will use default system timebase")
self.timebase = c_double(0)
def get_frame(self):
s, img = self.capture.read()
timestamp = time()
return Frame(timestamp,img)
def set_size(self,size):
width,height = size
self.capture.set(3, width)
self.capture.set(4, height)
def get_size(self):
return self.capture.get(3), self.capture.get(4)
def set_fps(self,fps):
self.capture.set(5,fps)
def get_fps(self):
return self.capture.get(5)
def get_now(self):
return time()
def create_atb_bar(self,pos):
size = 0,0
return size
def kill_atb_bar(self):
pass
def close(self):
pass
示例5: __init__
def __init__(self, mouse, n=1, data_dir='.', diff_thresh=80, resample=1, translation_max=50, smoothing_kernel=19, consecutive_skip_threshold=0.08, selection_from=[], point_mode='auto'):
self.mouse = mouse
self.n = n
self.data_dir = data_dir
# Parameters (you may vary)
self.diff_thresh = diff_thresh
self.resample = resample
self.translation_max = translation_max
self.kernel = smoothing_kernel
# Parameters (you should not vary)
self.cth1 = 0
self.cth2 = 0
plat = sys.platform
if 'darwin' in plat:
self.fourcc = CV_FOURCC('m','p','4','v')
elif plat[:3] == 'win':
self.fourcc = 1
else:
self.fourcc = -1
self.fh = FileHandler(self.data_dir, self.mouse, self.n)
self.framei = 0
self.load_time()
self.consecutive_skip_threshold = (self.fs/self.resample) * consecutive_skip_threshold
self.load_background()
self.height, self.width = self.background.shape
self.mov = VideoCapture(self.fh.get_path(self.fh.TRIAL, self.fh.MOV))
self.mov.read();self.time=self.time[1:]
#self.get_frame(self.mov,n=40) #MUST ADJUST TIME IF USING THIS
self.load_pts(mode=point_mode)
self.make_rooms()
示例6: __init__
def __init__(self, src,size=(640,480)):
self.controls = None
self.cvId = src
###add cv videocapture capabilities
self.cap = VideoCapture(src)
self.set_size(size)
self.read = self.cap.read
示例7: __init__
def __init__(self, title="Video Stream"):
''' Uses OpenCV 2.3.1 method of accessing camera '''
self.title = title
self.cap = VideoCapture(0)
self.prev = self.get_frame()
self.frame = self.get_frame()
namedWindow(title, 1)
示例8: __init__
class CaptureSource:
def __init__(self):
self._video = None
self._image = None
def get_resolution(self):
if (self._video):
return (int(self._video.get(CAP_PROP_FRAME_WIDTH)),
int(self._video.get(CAP_PROP_FRAME_HEIGHT)))
def camera(self, num_cams):
cam = Cameras()
cam.check_cameras(num_cams)
self._video = cam.show_and_select_camera()
def video(self, filename):
self._video = VideoCapture(filename)
def image(self, filename):
self._image = filename
def get_frame(self):
if self._video:
retval, frame = self._video.read()
return retval, frame
return True, imread(self._image)
示例9: caputure
def caputure():
# open Camera
cam = VideoCapture(0)
if not cam.isOpened():
LOGGER.debug('FAILED to open camera!!!')
return None
# capture image
for i in range(100):
status, img = cam.read()
if not status:
LOGGER.debug('FAiLED to capture image!!!')
return None
cam.release()
return img
示例10: __init__
def __init__(self, camera, dic=None):
self.camera = int(camera)
self.cap = VideoCapture(self.camera)
if dic:
for propID, value in dic.iteritems():
self.cap.set(propID, value)
first_frame = self.frame()
示例11: __init__
def __init__(self, cam_num = -1, resolution = (640, 480)):
'''
create camera object
cam_num device number (integer)
resolution image resolution (tuple width x height)
'''
self.device = cam_num
self.resolution = resolution
self.BGRimage = []
self.HSVimage = []
self.RGBimage = []
self.FPS = [0, 0]
self.__avr = 0
#assign and open device
self.__capture = VideoCapture(cam_num)
self.__capture.set(CV_CAP_PROP_FRAME_WIDTH,resolution[0])
self.__capture.set(CV_CAP_PROP_FRAME_HEIGHT,resolution[1])
self.__capture.open
self.__flag = False
t0 = time()
self.__flag, self.BGRimage = self.__capture.read()
self.FPS[0] = 1/(time()-t0)
self.FPS[1] = self.FPS[0]
self.__avr = self.FPS[0]
print "camera", self.device, "ready @", self.FPS[0], "fps"
return
示例12: Camera
class Camera(object):
"""
The class responsible for communicating with the actual camera and
getting images from it.
Attributes:
cam: An instance of an openCV VideoCapture.
"""
def __init__(self, device_num):
"""
Uses a device num in case the system has multiple cameras attached.
"""
self.cam = VideoCapture(device_num)
def get_image(self):
"""
Grab a frame from the camera. The cameraCommunicator is the caller,
and is responsible for lighting and location. The filename of the
image is returned.
Raises:
FatalCameraException: An image was not taken successfully.
"""
#create the systematic filename
timestamp = datetime.datetime.now()
filename = utils.get_image_dir() + str(timestamp.date()) + \
str(timestamp.hour) + str(timestamp.minute) + \
str(timestamp.second) + '.jpg'
#A series of reads to allow the camera to adjust to lighting
self.cam.read()
self.cam.read()
self.cam.read()
self.cam.read()
#only the last is saved
success, image = self.cam.read()
if not success:
raise FatalCameraException()
else:
imwrite(filename, image)
return timestamp, filename
示例13: __init__
def __init__(self, mouse, mode, data_directory='.', diff_thresh=100, resample=8, translation_max=100, smoothing_kernel=19, consecutive_skip_threshold=2, selection_from=[]):
self.mouse = mouse
self.data_dir = data_directory
self.mode = mode
self.selection_from = selection_from
# Parameters (you may vary)
self.diff_thresh = diff_thresh
self.resample = resample
self.translation_max = translation_max
self.kernel = smoothing_kernel
self.consecutive_skip_threshold = (37./self.resample) * consecutive_skip_threshold
# Parameters (you should not vary)
self.duration = 1
self.cth1 = 0
self.cth2 = 0
plat = sys.platform
if 'darwin' in plat:
self.fourcc = CV_FOURCC('m','p','4','v')
elif plat[:3] == 'win':
self.fourcc = 1
else:
self.fourcc = -1
fh = FileHandler(self.data_dir, self.mouse)
self.background_name = fh[mode][BACKGROUND][NAME]
self.background_dir = fh[mode][BACKGROUND][DIR]
self.trial_name = fh[mode][TRIAL][NAME]
self.trial_dir = fh[mode][TRIAL][DIR]
self.background, self.background_image = self.load_background()
self.height, self.width = np.shape(self.background)
timefile = os.path.join(self.trial_dir, self.trial_name+'-timestamps.json')
self.time = json.loads(open(timefile,'r').read())
vidfile = os.path.join(self.trial_dir, self.trial_name+'-cam.avi')
if not os.path.exists(vidfile):
vidfile = os.path.join(self.trial_dir, self.trial_name+'-cam0.avi')
if not os.path.exists(vidfile):
raise Exception('Movie %s not found.'%vidfile)
self.mov = VideoCapture(vidfile)
self.results = {}
self.results['centers'] = []
self.results['centers_all'] = []
self.results['left'] = 0
self.results['right'] = 0
self.results['middle'] = 0
self.results['left_assumed'] = 0
self.results['right_assumed'] = 0
self.results['middle_assumed'] = 0
self.results['skipped'] = 0
self.results['heat'] = np.zeros(np.shape(self.background))
self.results['n_frames'] = 0
self.results['params'] = [self.diff_thresh, self.kernel, self.translation_max, self.resample]
self.results['params_key'] = ['diff_thresh','kernel','translation_max','resample']
self.path_l, self.path_r, self.path_c, self.rooms_mask, self.paths_ignore, self.last_center = self.get_pt_selections()
示例14: __init__
def __init__(self,src_id,size=(640,480),fps=None):
self.controls = None
self.cvId = src_id
self.name = "VideoCapture"
self.controls = None
###add cv videocapture capabilities
self.capture = VideoCapture(src_id)
self.set_size(size)
示例15: grabImageFromUSB
def grabImageFromUSB(cameraNumber=0):
'''Grabs a snapshot from the specified USB camera.
Returns bool, video frame decoded as a JPEG bytearray.
'''
from cv2 import VideoCapture, imencode
# initialize the camera
cam = VideoCapture(cameraNumber)
retVal, rawData = cam.read()
if not retVal:
# frame captured returns errors
return False, None
retVal, jpgData = imencode('.jpg', rawData)
if not retVal:
# image encode errors
return False, None
return retVal, bytearray(jpgData)