命名管道(Named Pipe),也被稱為FIFO,是一種在UNIX、Linux和類Unix系統(tǒng)中用于實(shí)現(xiàn)進(jìn)程間通信(IPC)的機(jī)制。在Python中,我們可以使用os
模塊來創(chuàng)建和操作命名管道。
命名管道實(shí)際上是個(gè)特殊的文件,需要先創(chuàng)建
# 創(chuàng)建命名管道
os.mkfifo(pipe_name)
讀寫前后需要打開關(guān)閉
# 打開備寫
pipeout = os.open(pipe_name, os.O_WRONLY)
# 寫入數(shù)據(jù)
os.write(pipeout, framedata)
# 關(guān)閉管道
os.close(pipeout)
ffmpeg從命名管道輸入源的方法與普通文件輸入類似文章來源:http://www.zghlxwxcb.cn/news/detail-853740.html
# 從管道輸入輸入rawvideo
video_in = ffmpeg.input(PIPE_VIDEO_PATH, format='rawvideo', pix_fmt='bgr24', s="{}x{}".format(VIDEO_WIDTH, VIDEO_HEIGHT))
完整代碼,推流或生成視頻僅需輸入目標(biāo)rtmp:文章來源地址http://www.zghlxwxcb.cn/news/detail-853740.html
# coding: utf-8
import os
import time
import cv2
import ffmpeg
VIEW_PATH = 'view'
VIDEO_WIDTH = 1280
VIDEO_HEIGHT = 720
PIPE_VIDEO_PATH = '/tmp/pipe'
try:
# 創(chuàng)建命名管道
os.mkfifo( PIPE_VIDEO_PATH )
except OSError:
print("mkfifo error:", OSError)
def main(rtmp='test.flv'):
global VIDEO_HEIGHT
global VIDEO_WIDTH
filepath = os.path.join(VIEW_PATH, 'p640x1.jpg')
src_img=cv2.imread(filepath)
height, width, channels = src_img.shape
VIDEO_HEIGHT = height
VIDEO_WIDTH = width
print('INFO', "height, width, channels : {} {} {}".format(height, width, channels))
process_stdin = ffmpeg_process(rtmp)
pipeout = os.open(PIPE_VIDEO_PATH, os.O_WRONLY) #打開命名管道準(zhǔn)備寫入
s = time.time()
count = 0
while True:
if count >= 10*25: #目標(biāo)視頻時(shí)長10秒
break
os.write(pipeout, src_img.tobytes())
count+=1
os.close(pipeout)
process_stdin.stdin.close()
process_stdin.wait()
print(time.time()-s)
return 0
def ffmpeg_process(rtmp):
# 從管道輸入輸入rawvideo
video_in = ffmpeg.input(PIPE_VIDEO_PATH, format='rawvideo', pix_fmt='bgr24', s="{}x{}".format(VIDEO_WIDTH, VIDEO_HEIGHT))
process_stdin = (
ffmpeg
.output(
video_in,
rtmp,
#loglevel='quiet',
vcodec='libx264',
#acodec='aac',
threads='3',
# ac='2',
# ar='44100',
# ab='320k',
preset='ultrafast',
tune='zerolatency',
f='flv'
)
.overwrite_output()
#.run_async(cmd=["ffmpeg", "-re"],pipe_stdin=True) #推流
.run_async(cmd=["ffmpeg"],pipe_stdin=True) #生成視頻不用-re
)
return process_stdin
if __name__ == '__main__':
main()
到了這里,關(guān)于使用 ffmpeg-python+命名管道進(jìn)行圖片轉(zhuǎn)視頻或推流的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!