基本思想: 合并多個視訊;進行視訊截取;旋轉視訊;往視訊上寫入幀号;
合并視訊:
from moviepy.editor import *
import os
L = []
for root, dirs, files in os.walk("./"):
files.sort()
for file in files:
if os.path.splitext(file)[1] == '.mp4':
filePath = os.path.join(root, file)
video = VideoFileClip(filePath)
L.append(video)
print(L)
final_clip = concatenate_videoclips(L)
final_clip.to_videofile("./target.mp4", fps=30, remove_temp=False)
裁剪視訊
ffmpeg -ss 0:1:30 -t 0:0:20 -i input.avi -vcodec copy -acodec copy output.avi //剪切視訊
旋轉視訊
import numpy as np
import cv2
from PIL import Image
fps= 24
size=(1280,720)
cap = cv2.VideoCapture('source.mp4')
video_writer = cv2.VideoWriter("TEST.mp4", cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
def rotate_bound(image,angle):
#擷取圖像的尺寸
#旋轉中心
(h,w) = image.shape[:2]
(cx,cy) = (w/2,h/2)
#設定旋轉矩陣
M = cv2.getRotationMatrix2D((cx,cy),-angle,1.0)
cos = np.abs(M[0,0])
sin = np.abs(M[0,1])
# 計算圖像旋轉後的新邊界
nW = int((h*sin)+(w*cos))
nH = int((h*cos)+(w*sin))
# 調整旋轉矩陣的移動距離(t_{x}, t_{y})
M[0,2] += (nW/2) - cx
M[1,2] += (nH/2) - cy
return cv2.warpAffine(image,M,(nW,nH))
while(cap.isOpened()):
ret, frame = cap.read()
img2 = rotate_bound(frame,180)
video_writer.write(img2)
cap.release()
cv2.destroyAllWindows()
import cv2
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np
vc = cv2.VideoCapture('/home/ubuntu/Downloads/33.mp4') # 讀入視訊檔案,命名cv
fps= 24
size=(1280,720)
video_writer = cv2.VideoWriter("TEST.mp4", cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
rval= True
i = 0
while rval:
rval, frame = vc.read()
if not rval:
break
cv2img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pilimg = Image.fromarray(cv2img)
draw = ImageDraw.Draw(pilimg)
font = ImageFont.truetype("simhei.ttf", 60, encoding="utf-8")
draw.text((0, 0), str(i), (255, 0, 0), font=font)
i=i+1
cv2charimg = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)
cv2.imshow("photo", cv2charimg)
video_writer.write(cv2charimg)
cv2.waitKey (1)
video_writer.release()
cv2.destroyAllWindows()
import cv2
import numpy as np
default_video="a.mp4"
confidence_video="b.mp4"
cam1 = cv2.VideoCapture(default_video)
cam2 = cv2.VideoCapture(confidence_video)
ww = int(cam1.get(3))
hh = int(cam1.get(4))
print(ww, hh)
print(cam1.get(cv2.CAP_PROP_FPS))
CAMERA_FPS = cam1.get(cv2.CAP_PROP_FPS) # 25幀/秒
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
videoWriter = cv2.VideoWriter('./a.mp4', fourcc, CAMERA_FPS,(hh * 2, hh))
while True:
# 讀取視訊
(ok1, frame1) = cam1.read()
(ok2, frame2) = cam2.read()
if ok1 and ok2:
frame1 = cv2.resize(frame1, (hh, hh))
frame2 = cv2.resize(frame2, (hh, hh))
cv2.putText(frame1, "default algorithm", (250, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1)
cv2.putText(frame2, "confidence algorithm", (250, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1)
image = np.concatenate([frame1, frame2], axis=1)
cv2.namedWindow("V",0)
cv2.imshow("V", image)
videoWriter.write(image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
videoWriter.release()
cam1.release()
cam2.release()
cv2.destroyAllWindows()