本文整理汇总了Python中cv2.VideoWriter方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.VideoWriter方法的具体用法?Python cv2.VideoWriter怎么用?Python cv2.VideoWriter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.VideoWriter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: encode
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def encode(self, video_in, data, video_out):
assert len(data) == self.data_dim
video_in = cv2.VideoCapture(video_in)
width = int(video_in.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_in.get(cv2.CAP_PROP_FRAME_HEIGHT))
length = int(video_in.get(cv2.CAP_PROP_FRAME_COUNT))
data = torch.FloatTensor([data]).cuda()
video_out = cv2.VideoWriter(
video_out, cv2.VideoWriter_fourcc(*'mp4v'), 20.0, (width, height))
for i in tqdm(range(length)):
ok, frame = video_in.read()
frame = torch.FloatTensor([frame]) / 127.5 - 1.0 # (L, H, W, 3)
frame = frame.permute(3, 0, 1, 2).unsqueeze(0).cuda() # (1, 3, L, H, W)
wm_frame = self.encoder(frame, data) # (1, 3, L, H, W)
wm_frame = torch.clamp(wm_frame, min=-1.0, max=1.0)
wm_frame = (
(wm_frame[0, :, 0, :, :].permute(1, 2, 0) + 1.0) * 127.5
).detach().cpu().numpy().astype("uint8")
video_out.write(wm_frame)
video_out.release()
示例2: enable_videowriter
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def enable_videowriter(self, output_filename, fourcc_string="MJPG",
fps=None):
""" Write images to video file.
Parameters
----------
output_filename : str
Output filename.
fourcc_string : str
The OpenCV FOURCC code that defines the video codec (check OpenCV
documentation for more information).
fps : Optional[float]
Frames per second. If None, configured according to current
parameters.
"""
fourcc = cv2.VideoWriter_fourcc(*fourcc_string)
if fps is None:
fps = int(1000. / self._update_ms)
self._video_writer = cv2.VideoWriter(
output_filename, fourcc, fps, self._window_shape)
示例3: write
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def write(self, filename, frames, fps, show=False):
fps = max(1, fps)
out = None
try:
for image in frames:
frame = cv2.imread(image)
if show:
cv2.imshow('video', frame)
if not out:
height, width, channels = frame.shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(filename, fourcc, 20, (width, height))
out.write(frame)
finally:
out and out.release()
cv2.destroyAllWindows()
示例4: VideoWriter
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def VideoWriter(fn: Path, cc4: str, xypix: tuple, fps: float, usecolor: bool):
"""
Parameters
----------
fn: pathlib.Path
output filename to write
cc4: str
four character fourcc code e.g. 'FFV1'
xypix: two-element tuple with x,y pixel count
usecolor: bool color or bw
"""
fn.parent.mkdir(parents=True, exist_ok=True)
ncc4 = cv2.VideoWriter_fourcc(*cc4)
hv = cv2.VideoWriter(str(fn), ncc4, fps=fps, frameSize=xypix, isColor=usecolor)
if not hv or not hv.isOpened():
raise RuntimeError(f'trouble starting video {fn}')
yield hv
hv.release()
示例5: main
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def main(track_log_dir, output_path, videoname):
track_log_dir = osp.join(track_log_dir)
te_bboxs = readbbox(osp.join(track_log_dir, 'track_rect.txt'))
num_frames = len(te_bboxs)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
org_img = cv2.imread(osp.join(track_log_dir, 'image_origin{}.jpg'.format(1)))
out = cv2.VideoWriter(osp.join(output_path, videoname + '.avi'), fourcc, 24.0, (org_img.shape[1], org_img.shape[0]))
print(org_img.shape)
for i in range(1, num_frames):
org_img = cv2.imread(osp.join(track_log_dir, 'image_origin{}.jpg'.format(i)))
bbox = te_bboxs[i]
cv2.rectangle(org_img, (int(bbox[0]), int(bbox[1])),
(
int(bbox[0]) + int(bbox[2]),
int(bbox[1]) + int(bbox[3])),
(0, 0, 255), 2)
cv2.imshow('frame', org_img)
out.write(org_img)
cv2.waitKey(1)
out.release()
cv2.destroyAllWindows()
示例6: show
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def show(self):
img_list=[x for x in os.listdir(self.img_path) if 'jpg' in x or 'JPEG' in x]
img_list.sort()
f=open(self.label_path,'r')
t=time.time()
im=cv2.imread(os.path.join(self.img_path,img_list[0]))
fourcc=cv2.VideoWriter_fourcc('M','J','P','G')
img_h,img_w,_=im.shape
videoWriter=cv2.VideoWriter(os.path.join('../data/vedio','car2.mp4'),fourcc,30,(img_w,img_h))
for img in img_list:
line=f.readline().strip('\n')
box=line.split(',')
box=[int(float(box[0])),int(float(box[1])),int(float(box[2])),int(float(box[3]))]
box[2]=box[0]+box[2]
box[3]=box[1]+box[3]
im=cv2.imread(os.path.join(self.img_path,img))
videoWriter.write(im)
cv2.rectangle(im,(box[0],box[1]),(box[2],box[3]),(0,0,255),1)
cv2.imshow('img',im)
cv2.waitKey(10)
f.close()
cv2.destroyAllWindows()
videoWriter.release()
print(time.time()-t)
示例7: write_video
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def write_video(file_path, frames, fps):
"""
Writes frames to an mp4 video file
:param file_path: Path to output video, must end with .mp4
:param frames: List of PIL.Image objects
:param fps: Desired frame rate
"""
w, h = frames[0].size
fourcc = cv.VideoWriter_fourcc('m', 'p', '4', 'v')
writer = cv.VideoWriter(file_path, fourcc, fps, (w, h))
for frame in frames:
writer.write(pil_to_cv(frame))
writer.release()
示例8: _create_video_writer
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def _create_video_writer(self) -> Optional[cv2.VideoWriter]:
if not self.output_dir:
return None
ext = self.config.demo.output_file_extension
if ext == 'mp4':
fourcc = cv2.VideoWriter_fourcc(*'H264')
elif ext == 'avi':
fourcc = cv2.VideoWriter_fourcc(*'PIM1')
else:
raise ValueError
output_path = self.output_dir / f'{self._create_timestamp()}.{ext}'
writer = cv2.VideoWriter(output_path.as_posix(), fourcc, 30,
(self.gaze_estimator.camera.width,
self.gaze_estimator.camera.height))
if writer is None:
raise RuntimeError
return writer
示例9: consume
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def consume(self, item : np.array):
'''
Receives the picture frame to append to the video and appends it to the video.
If it is the first frame received, it opens the video file and determines \
the height and width of the video from the dimensions of that first frame. \
Every subsequent frame is expected to have the same height and width. If it \
does not has it, it gets resized to it.
- Arguments:
- item: np.array of dimension (height, width, 3)
'''
if self._out is None:
self._height = item.shape[0]
self._width = item.shape[1]
self._out = cv2.VideoWriter(self._video_file, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), self._fps, (self._width, self._height))
resized = cv2.resize(item, (self._width, self._height), interpolation = cv2.INTER_AREA)
if self._swap_channels:
resized = resized[...,::-1]
self._out.write(resized)
示例10: __init__
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def __init__(self):
self.open = True
self.device_index = 0
self.fps = 6 # fps should be the minimum constant rate at which the camera can
self.fourcc = "MJPG" # capture images (with no decrease in speed over time; testing is required)
self.frameSize = (640,480) # video formats and sizes also depend and vary according to the camera used
self.video_filename = "temp_video.avi"
self.video_cap = cv2.VideoCapture(self.device_index)
self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc)
self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize)
self.frame_counts = 1
self.start_time = time.time()
# Video starts being recorded
示例11: draw_video
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def draw_video(prefix1, prefix2, ratio):
draw_imgs(prefix1, ratio, mode=1)
draw_imgs(prefix2, ratio, mode=2)
fps = 25
size = (2000, 2000)
videowriter = cv2.VideoWriter("./figures/demo_2D_distribution_noise-%d%%.avi" % ratio, cv2.cv.CV_FOURCC(*"MJPG"), fps, size)
for _iter in xrange(1000, 200000+1, 100):
if not choose_iter(_iter, 100):
continue
image_file1 = "./figures/%s_2D_dist_%d.jpg" % (prefix1, _iter)
img1 = cv2.imread(image_file1)
h1, w1, c1 = img1.shape
image_file2 = "./figures/%s_2D_dist_%d.jpg" % (prefix2, _iter)
img2 = cv2.imread(image_file2)
h2, w2, c2 = img2.shape
assert h1 == h2 and w1 == w2
img = np.zeros((h1, w1+w2, c1), dtype=img1.dtype)
img[0:h1, 0:w1, :] = img1
img[0:h1, w1:w1+w2, :] = img2
videowriter.write(img)
示例12: __init__
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def __init__(self,video=False):
self.config = json.load(open('../config3.json'))
self.video=video
print(self.config)
self.options = self.config['yoloConfig']
self.tfnet = TFNet(self.options)
self.predictThresh = 0.05
self.getAnnotations()
print(self.anotations_list)
if self.video:
# self.cap = cv2.VideoCapture(0)
self.cap = cv2.VideoCapture('../../WPI_vdo.mov')
self.out = cv2.VideoWriter('output.avi',-1, 20.0, (640,480))
示例13: _startRecording
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def _startRecording(self):
if self.outputDirectory is None:
return self.setError("output directory is not specified")
if None in [self.frameWidth, self.frameHeight]:
return self.setError("resolution is't specified")
fourcc = cv.VideoWriter_fourcc(*config.FOURCC_CODEC)
videoSize = (self.frameWidth, self.frameHeight)
# calculation output filename
now = dts.datetime.utcnow()
fileName = "video_{}{}".format(now.strftime("%Y%m%dT%H%M%S"), config.OUTPUT_FILES_EXTENSION)
subFolder = self._getSubFolderName(now)
if subFolder is not None:
needCreate = ((self.__prevSubFolder is not None) or (subFolder != self.__prevSubFolder))
dirName = os.path.join(self.outputDirectory, subFolder)
dirName = os.path.normpath(dirName)
if (needCreate) and (not os.path.exists(dirName)):
self.logger.info("adding new directory: {}".format(dirName))
if not mkdir_p(dirName):
return self.setError("can't create sub-directory: {}".format(dirName))
fileName = os.path.join(dirName, fileName)
else:
fileName = os.path.join(self.outputDirectory, fileName)
self.__output = cv.VideoWriter(fileName, fourcc, config.OUTPUT_FRAME_RATE, videoSize)
self.__isRecording = True
return True
示例14: _startRecording
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def _startRecording(self):
if self.outputDirectory is None:
return self.setError("output directory is not specified")
if None in [self.frameWidth, self.frameHeight]:
return self.setError("resolution is't specified")
fourcc = cv.VideoWriter_fourcc(*config.FOURCC_CODEC)
videoSize = (self.frameWidth, self.frameHeight)
# calculation output filename
now = dts.datetime.utcnow()
fileName = "video_{}{}".format(now.strftime("%Y%m%dT%H%M%S"), config.OUTPUT_FILES_EXTENSION)
subFolder = self._getSubFolderName(now)
if subFolder is not None:
needCreate = ((self._prevSubFolder is not None) or (subFolder != self._prevSubFolder))
dirName = os.path.join(self.outputDirectory, subFolder)
dirName = os.path.normpath(dirName)
if (needCreate) and (not os.path.exists(dirName)):
self.logger.info("adding new directory: {}".format(dirName))
if not mkdir_p(dirName):
return self.setError("can't create sub-directory: {}".format(dirName))
fileName = os.path.join(dirName, fileName)
else:
fileName = os.path.join(self.outputDirectory, fileName)
self._output = cv.VideoWriter(fileName, fourcc, config.OUTPUT_FRAME_RATE, videoSize)
self._isRecording = True
return True
示例15: add_water_mask
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter [as 别名]
def add_water_mask(video_path, mask_word):
"""
给视频增加水印
:param video_part3: 视频源
:param mask_word: 水印文字
:return:
"""
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
# 保证帧率不变
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
video_temp_path = get_temp_path(video_path, 'temp')
video_writer = cv2.VideoWriter(video_temp_path, fourcc, fps, img_size)
ret, frame = cap.read()
while ret:
# 文字在图中的坐标(注意:这里的坐标原点是图片左上角)
x, y = img_size[0] - 200, img_size[1] - 50
cv2.putText(img=frame, text=mask_word,
org=(x, y), fontFace=cv2.FONT_HERSHEY_COMPLEX_SMALL,
fontScale=1, color=(255, 255, 255))
video_writer.write(frame)
ret, frame = cap.read()
# 删除源文件,并重命名临时文件
os.remove(video_path)
os.rename(video_temp_path, video_path)
print('水印添加完成~')
video_writer.release()
cap.release()