def make_video(self, images, outimg=None, fps=2, size=None, is_color=True, format="XVID", outvid='image_video.avi'):
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
fourcc = VideoWriter_fourcc(*format)
vid = None
for image in images:
if not os.path.exists(image):
raise FileNotFoundError(image)
img = imread(image)
if vid is None:
if size is None:
size = img.shape[1], img.shape[0]
vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
if size[0] != img.shape[1] and size[1] != img.shape[0]:
img = resize(img, size)
vid.write(img)
vid.release()
return vid
# Un radio de 4 pixeles es equivalente a un radio de 0.0002 en wcs
python类VideoWriter()的实例源码
def video (seconds, frameRate):
cap = cv2.VideoCapture(0)
if(not cap.isOpened()):
return "error"
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'XVID')
name = "media/video/" + time.strftime("%d-%m-%Y_%X")+".avi"
out = cv2.VideoWriter(name, fourcc, frameRate, (640,480))
program_starts = time.time()
result = subprocess.Popen(["ffprobe", name], stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell=True)
nFrames=0
while(nFrames<seconds*frameRate):
ret, frame = cap.read()
if ret==True:
out.write(frame)
nFrames += 1
else:
break
cap.release()
return name
def dump_video(filename, clip, fourcc_str='X264', fps=30.0):
"""Write video on disk from a stack of images
Parameters
----------
filename : str
Fullpath of video-file to generate
clip : ndarray
ndarray where first dimension is used to refer to i-th frame
fourcc_str : str
str to retrieve fourcc from opencv
fps : float
frame rate of create video-stream
"""
fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str))
fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2])
if fid.isOpened():
for i in xrange(clip.shape[0]):
fid.write(clip[i, ...])
return True
else:
return False
def applyTransform(self):
self.framing(self.path)
self.height,self.width=cv2.imread("Frames/1.jpg").shape[:2]
# write transformed video
out = cv2.VideoWriter("changedOutput.mp4",cv.CV_FOURCC('a','v','c','1'), 30.0, (self.width, self.height))
folder=self.sort_files()
# write Transformed video frames
for i in folder:
pic="Frames/"+str(i)+".jpg"
Newpic=cv2.imread(pic,0)
frame=cv2.Canny(Newpic,100,200)
cv2.imwrite(pic,frame)
Newpic=cv2.imread(pic)
img=cv2.flip(Newpic,0)
out.write(img)
out.release()
# Writing output video file
def save_avi(reader, output_filename):
try:
import cv2
except ImportError:
print('Please install OpenCV2 to use this format.')
raise
writer = cv2.VideoWriter(output_filename, cv2.VideoWriter_fourcc(*'PIM1'),
25, reader.image_size1, False)
ts = []
for t, img in reader:
ts.append(t)
writer.write(img)
write_timestamps(output_filename + '.txt', ts)
def __init__(self, output_width, output_height, output_fps, output_format, output_path):
self.frame_wrappers = []
self.start_time = -1
self.end_time = -1
self.pub_img = None
self.bridge = CvBridge()
self.fps = output_fps
self.interval = 1.0 / self.fps
self.output_width = output_width
self.output_height = output_height
if opencv_version() == 2:
fourcc = cv2.cv.FOURCC(*output_format)
elif opencv_version() == 3:
fourcc = cv2.VideoWriter_fourcc(*output_format)
else:
raise
self.output_path = output_path
self.video_writer = cv2.VideoWriter(output_path, fourcc, output_fps, (output_width, output_height))
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)
def init_video_writer(fourcc):
global IS_CAPTURING
global OUT
global CURRENT_CAPTURE
path = './avi/'
if not os.path.exists(path):
os.makedirs(path)
log('STARTING CAPTURE')
filename = str(datetime.datetime.now()).replace(" ", "_").replace(":","_")[:-7] + ".avi"
OUT = cv2.VideoWriter(path + filename, fourcc, SETTINGS['output_fr'], (500, 375))
CURRENT_CAPTURE = path + filename
IS_CAPTURING = True
def run(self):
while True:
if self.flag:
ret, image = self.camera.read()
if image is None:
break
color_swapped_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
height, width, _ = color_swapped_image.shape
qt_image = QImage(color_swapped_image.data,
width,
height,
color_swapped_image.strides[0],
QImage.Format_RGB888)
pixmap = QPixmap(qt_image)
pixmap = pixmap.scaled(self.videoLabel.geometry().width(), self.videoLabel.geometry().height())
if self.start_flag and self.support_flag:
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
self.path = "appdata/" + self.cap.guide.dataset_type + "/data/" + self.cap.date_str + "-" + str(
self.cap.guide.gesture_type) + ".avi"
self.out = cv2.VideoWriter(self.path, fourcc, 20.0, (640, 480))
self.support_flag = False
if self.name == "Camera" and self.out is not None:
self.image_siganl.emit(image)
self.videoLabel.setPixmap(pixmap)
if self.name == "Video":
time.sleep(1/self.fps)
else:
pass
def __init__(self, args, main_out_vid_name="foreground"):
self.mask_writer = None
super().__init__(args, main_out_vid_name)
if args.mask_output_video == "":
args.mask_output_video = args.in_video[:-4] + "_bs_mask.mp4"
self.mask_writer = cv2.VideoWriter(os.path.join(self.datapath, args.mask_output_video),
cv2.VideoWriter_fourcc('X', '2', '6', '4'),
self.cap.get(cv2.CAP_PROP_FPS),
(int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))),
False)
self.mask_writer.set(cv2.VIDEOWRITER_PROP_NSTRIPES, cpu_count())
self.foreground_writer = self.writer
self.foreground = None
self.mask = None
motionDetectionPiMultiProcessing_COM_LiveFeed.py 文件源码
项目:smart-cam
作者: smart-cam
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def videoWriter(cam_writer_frames_Queue, writer_blurrer_filename_Queue):
while True:
startTime, FRAMES = cam_writer_frames_Queue.get()
t1 = time.time()
# Writing frames to disk
#fourcc = cv2.cv.CV_FOURCC(*'XVID')
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
fourcc_out = cv2.VideoWriter_fourcc(*'avc1')
filename_blurs = 'blurrer' + '_' + RPiName + '_' + repr(startTime) + ".avi"
clipWriter = cv2.VideoWriter(filename_blurs, fourcc, 10, (320, 240))
for frameTimestamp, frame in FRAMES:
clipWriter.write(frame)
writer_blurrer_filename_Queue.put(filename_blurs)
filename = RPiName + '_' + repr(startTime) + ".mp4"
clipWriter = cv2.VideoWriter(filename, fourcc_out, 10, (320, 240))
while len(FRAMES) > 0:
frameTimestamp, frame = FRAMES.pop(0)
frameWithCaption = writeToFrame(frameTimestamp, frame, RPiName)
clipWriter.write(frameWithCaption)
print "Written to disk: ", time.time() - t1
def run(self):
filename = '.' + filename_tmpl.format(self.date, 0, self.extension)
print('Starting new video File [{}]'.format(filename))
video = cv2.VideoWriter(filename, self.fourcc, self.fps, self.size)
while True:
f = self.queue.get()
if f is QueueFinished:
self.queue.task_done()
break
video.write(f)
self.queue.task_done()
duration = (datetime.now() - self.date).total_seconds()
new_filename = filename_tmpl.format(self.date, round(duration), self.extension)
print('Releasing resources for [{}] and renaming it to [{}]'.format(filename, new_filename))
video.release()
os.rename(filename, new_filename)
try:
redis.publish('video:new', new_filename)
except:
print("Error publishing {} to redis".format(new_filename), file=sys.stderr)
def put(self, name, frame):
if self.type==self.DIR:
cv2.imwrite(self.path+"/"+name, frame)
elif self.type==self.IMG:
cv2.imwrite(self.path, frame)
elif self.type==self.VID:
if self.writer is None:
if hasattr(cv2, 'VideoWriter_fourcc'):
fcc=cv2.VideoWriter_fourcc(*'MJPG')
else:
fcc=cv2.cv.CV_FOURCC(*'MJPG')
self.writer = cv2.VideoWriter(self.path, fcc, int(self.fps), (frame.shape[1], frame.shape[0]))
self.writer.write(frame)
else:
pass
def _write_video(self, im):
if self.writer is None:
h, w = im.shape[:2]
self.writer = cv2.VideoWriter(self.filename, cv2.cv.CV_FOURCC(*'mp42'),
30.0, (w, h), im.ndim == 3)
print('{} :: creating {} ({},{})'.format(self.__class__.__name__, self.filename, w, h))
self.writer.write(im)
def write_video(fn, im, scale=1.0, as_images=False):
global g_fn_map
if fn not in g_fn_map:
g_fn_map[fn] = VideoWriter(fn, as_images=as_images)
im_scaled = im_resize(im, scale=scale) if scale != 1.0 else im
g_fn_map[fn].write(im_scaled)
# def write_images(template, im):
def make_video(self, images, outvid=None, fps=5, size=None, is_color=True, format="XVID"):
"""
Create a video from a list of images.
@param outvid output video
@param images list of images to use in the video
@param fps frame per second
@param size size of each frame
@param is_color color
@param format see http://www.fourcc.org/codecs.php
"""
# fourcc = VideoWriter_fourcc(*format)
# For opencv2 and opencv3:
if int(cv2.__version__[0]) > 2:
fourcc = cv2.VideoWriter_fourcc(*format)
else:
fourcc = cv2.cv.CV_FOURCC(*format)
vid = None
for image in images:
assert os.path.exists(image)
img = imread(image)
if vid is None:
if size is None:
size = img.shape[1], img.shape[0]
vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
if size[0] != img.shape[1] and size[1] != img.shape[0]:
img = resize(img, size)
vid.write(img)
vid.release()
def make_video(self, images, outvid=None, fps=5, size=None, is_color=True, format="XVID"):
"""
Create a video from a list of images.
@param outvid output video
@param images list of images to use in the video
@param fps frame per second
@param size size of each frame
@param is_color color
@param format see http://www.fourcc.org/codecs.php
"""
# fourcc = VideoWriter_fourcc(*format)
# For opencv2 and opencv3:
if int(cv2.__version__[0]) > 2:
fourcc = cv2.VideoWriter_fourcc(*format)
else:
fourcc = cv2.cv.CV_FOURCC(*format)
vid = None
for image in images:
assert os.path.exists(image)
img = imread(image)
if vid is None:
if size is None:
size = img.shape[1], img.shape[0]
vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
if size[0] != img.shape[1] and size[1] != img.shape[0]:
img = resize(img, size)
vid.write(img)
vid.release()
def make_video(images, outvid=None, fps=5, size=None, is_color=True, format="XVID"):
"""
Create a video from a list of images.
@param outvid output video
@param images list of images to use in the video
@param fps frame per second
@param size size of each frame
@param is_color color
@param format see http://www.fourcc.org/codecs.php
"""
# fourcc = VideoWriter_fourcc(*format)
# For opencv2 and opencv3:
if int(cv2.__version__[0]) > 2:
fourcc = cv2.VideoWriter_fourcc(*format)
else:
fourcc = cv2.cv.CV_FOURCC(*format)
vid = None
for image in images:
assert os.path.exists(image)
img = imread(image)
if vid is None:
if size is None:
size = img.shape[1], img.shape[0]
vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
if size[0] != img.shape[1] and size[1] != img.shape[0]:
img = resize(img, size)
vid.write(img)
vid.release()
def make_video(self, images, outvid=None, fps=5, size=None, is_color=True, format="XVID"):
"""
Create a video from a list of images.
@param outvid output video
@param images list of images to use in the video
@param fps frame per second
@param size size of each frame
@param is_color color
@param format see http://www.fourcc.org/codecs.php
"""
# fourcc = VideoWriter_fourcc(*format)
# For opencv2 and opencv3:
if int(cv2.__version__[0]) > 2:
fourcc = cv2.VideoWriter_fourcc(*format)
else:
fourcc = cv2.cv.CV_FOURCC(*format)
vid = None
for image in images:
assert os.path.exists(image)
img = imread(image)
if vid is None:
if size is None:
size = img.shape[1], img.shape[0]
vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
if size[0] != img.shape[1] and size[1] != img.shape[0]:
img = resize(img, size)
vid.write(img)
vid.release()
def __init__(self, file_loc,frame_rate,frame_size):
super().__init__()
self.writer = VideoWriter(file_loc, VideoWriter_fourcc(*'DIVX'), float(frame_rate), frame_size)
def addFrame(self, frame, width=300):
frame = imutils.resize(frame, width)
# check if the writer is None
if self.writer is None:
# store the image dimensions, initialzie the video writer,
# and construct the zeros array
(self.h, self.w) = frame.shape[:2]
self.writer = cv2.VideoWriter(self.output, self.fourcc, self.fps,
(self.w * 2, self.h * 2), True)
self.zeros = np.zeros((self.h, self.w), dtype="uint8")
# break the image into its RGB components, then construct the
# RGB representation of each frame individually
(B, G, R) = cv2.split(frame)
R = cv2.merge([self.zeros, self.zeros, R])
G = cv2.merge([self.zeros, G, self.zeros])
B = cv2.merge([B, self.zeros, self.zeros])
# construct the final output frame, storing the original frame
# at the top-left, the red channel in the top-right, the green
# channel in the bottom-right, and the blue channel in the
# bottom-left
output = np.zeros((self.h * 2, self.w * 2, 3), dtype="uint8")
output[0:self.h, 0:self.w] = frame
output[0:self.h, self.w:self.w * 2] = R
output[self.h:self.h * 2, self.w:self.w * 2] = G
output[self.h:self.h * 2, 0:self.w] = B
# write the output frame to file
self.writer.write(output)
def addFrame(self, frame, width=600):
frame = imutils.resize(frame, width)
# check if the writer is None
if self.writer is None:
# store the image dimensions, initialzie the video writer,
(self.h, self.w) = frame.shape[:2]
self.writer = cv2.VideoWriter(self.output, self.fourcc, self.fps,
(self.w, self.h), True)
# write the output frame to file
self.writer.write(frame)
def red_and_black():
red = cv2.imread('./data/redHDSolidBlock.jpg')
black = cv2.imread('./data/blackHDSolidBlock.jpg')
vwriter = VideoWriter('red_black_0.5Hz.avi')
frames = 0
for t in range(30):
for f in range(20):
vwriter.addFrame(black)
frames+=1
for f in range(20):
vwriter.addFrame(red)
frames+=1
vwriter.finalise()
print("Created movie with %d frames" % frames)
def webcam_capture_video(output = 'webcam.avi', duration = 5):
w = VideoWriter(output = output)
cap = cv2.VideoCapture(0)
t = t0 = time.time()
t1 = t + duration
md = []
while (t < t1):
_,f = cap.read()
w.addFrame(f)
md.append(t)
t = time.time()
w.finalise()
print("Captured %d frames to %s in %f\n" % (len(md), output, (t - t0)))
def write_labels(video, label_dict, secs=1):
cap = cv2.VideoCapture(video)
w=int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH ))
h=int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT ))
out = cv2.VideoWriter('output.mp4', -1, 20.0, (w,h))
f_no = 0
fps = get_frame_rate(cap)
inc = int(fps * secs)
f_nos = label_dict.keys()
lbl = ''
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
if f_no in f_nos:
try:
lbls = label_dict[f_no]
lbl = ",".join(lbls.keys())
except:
pass
cv2.putText(frame,lbl,(105, 105),cv2.FONT_HERSHEY_COMPLEX_SMALL,2,(0,0,255))
#out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
#inc
f_no += 1
cap.release()
out.release()
cv2.destroyAllWindows()
#if __name__ == '__main__' :
# get_frames_every_x_sec('video.mp4', '.')
def saveVideo3D(self, filename, sequence, showPC=True, showGT=False, niceColors=True, plotFrameNumbers=False,
height=400, width=400):
"""
Create a video with 3D annotations
:param filename: name of file to save
:param sequence: sequence data
:return: None
"""
txt = 'Saving {}'.format(filename)
pbar = pb.ProgressBar(maxval=self.joints.shape[0], widgets=[txt, pb.Percentage(), pb.Bar()])
pbar.start()
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'DIVX')
video = cv2.VideoWriter('{}/depth_{}.avi'.format(self.subfolder, filename), fourcc, self.fps, (height, width))
if not video:
raise EnvironmentError("Error in creating video writer")
for i in range(self.joints.shape[0]):
jt = self.joints[i]
img = self.plotResult3D_OS(sequence.data[i].dpt, sequence.data[i].T, sequence.data[i].gt3Dorig, jt,
showPC=showPC, showGT=showGT, niceColors=niceColors, width=width, height=height)
img = numpy.flipud(img)
img = img[:, :, [2, 1, 0]] # change color channels for OpenCV
img = cv2.resize(img, (height, width))
if plotFrameNumbers:
if sequence.data[i].subSeqName == 'ref':
cv2.putText(img, "Reference Frame {}".format(i), (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255))
# plot frame number
cv2.putText(img, "{}".format(i), (height-50, width-10), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255))
# write frame
video.write(img)
pbar.update(i)
video.release()
del video
cv2.destroyAllWindows()
pbar.finish()
def saveVideoFrames(self, filename, images):
"""
Create a video with synthesized images
:param filename: name of file to save
:param images: video data
:return: None
"""
txt = 'Saving {}'.format(filename)
pbar = pb.ProgressBar(maxval=images.shape[0], widgets=[txt, pb.Percentage(), pb.Bar()])
pbar.start()
height = width = 128
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'DIVX')
video = cv2.VideoWriter('{}/synth_{}.avi'.format(self.subfolder, filename), fourcc, self.fps, (height, width))
if not video:
raise EnvironmentError("Error in creating video writer")
for i in range(images.shape[0]):
img = images[i]
img = cv2.normalize(img, alpha=0, beta=255, norm_type=cv2.cv.CV_MINMAX, dtype=cv2.cv.CV_8UC1)
img = cv2.cvtColor(img, cv2.cv.CV_GRAY2BGR)
img = cv2.resize(img, (height, width))
# write frame
video.write(img)
pbar.update(i)
video.release()
del video
cv2.destroyAllWindows()
pbar.finish()
def convert_video(self, video_path, output_directory, skip=0, resize=400):
video = cv2.VideoCapture(video_path)
video_output = None
i = 0
img_init = None
while video.get(cv2.cv.CV_CAP_PROP_POS_AVI_RATIO) < 1.0:
i += 1
for _ in range(skip+1):
status, bgr_img = video.read()
img = PIL.Image.fromarray(cv2.cvtColor(
bgr_img,
cv2.COLOR_BGR2RGB
))
img = neural_art.utility.resize_img(img, resize)
if video_output is None:
video_output = cv2.VideoWriter(
"{}/out.avi".format(output_directory),
fourcc=0, #raw
fps=video.get(cv2.cv.CV_CAP_PROP_FPS) / (skip + 1),
frameSize=img.size,
isColor=True
)
if(not video_output.isOpened()):
raise(Exception("Cannot Open VideoWriter"))
if img_init is None:
img_init = img
converted_img = self.frame_converter.convert(img, init_img=img_init, iteration=self.iteration)
converted_img.save("{}/converted_{:05d}.png".format(output_directory, i))
img_init = converted_img
video_output.write(cv2.cvtColor(
numpy.asarray(converted_img),
cv2.COLOR_RGB2BGR
))
video_output.release()
def __init__(self, IP, PORT, CameraID, parent=None):
"""
Initialization.
"""
self._image = None
self._imgWidth = 320
self._imgHeight = 240
self._cameraID = CameraID
# Proxy to ALVideoDevice.
self._videoProxy = None
# Our video module name.
self._imgClient = ""
# This will contain this alImage we get from Nao.
self._alImage = None
self._registerImageClient(IP, PORT)
# Trigger 'timerEvent' every ms.
self.delay=0.1
self.opencvframe=None
# Show opencv image
self.showvideo=False
self.output_path='./data/'+datetime.datetime.now().strftime('%Y_%m_%d_%H_%M')+'/'
# Define the codec and create VideoWriter object
self.enabledwriter=False
self._fps=2.0
self.outvideo=self.output_path+'log.avi'
self._fourcc = cv2.cv.FOURCC(*'XVID')
self._out =None
self.numframe=0
def initWriter(self):
if not os.path.exists(self.output_path):
os.makedirs(self.output_path)
self._out = cv2.VideoWriter(self.outvideo, self._fourcc, self._fps, (self._imgWidth,self._imgHeight))
self.enabledwriter=True