python opencv ffmpeg的使用

用cv2抓取本机摄像头,并且窗口预览,并用ffmpeg,udp协议进行推流,延时在1秒左右。

import time

import cv2

import ffmpeg

import numpyas np

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

cap.set(cv2.CAP_PROP_FPS,16)

width =640

height =480

video_format =”h264″

server_url =”udp://127.0.0.1:1234″

process2 = (

ffmpeg

.input( pipe: ,format= rawvideo ,pix_fmt= bgr24 ,s= {}x{} .format(width, height))

.output(server_url,vcodec=”libx264″,format=video_format,pkt_size=1316,preset=”ultrafast”,tune=”zerolatency”)

.overwrite_output()

.run_async(pipe_stdin=True)

)

flag=0

def frame_to2(out_frame):

global flag

if(flag==1):

flag=0

        else:

process2.stdin.write(

out_frame

.astype(np.uint8)

.tobytes()

)

flag=0

    # 逐帧捕获

while True:

ret, frame = cap.read()

# 如果正确读取帧,ret为True

    if not ret:

print(“Can t receive frame (stream end?). Exiting …”)

break;

#如下通过frame.shape获取摄像头逐帧分辨率,by Navy 2022-03-31

# print(frame.shape)

    #frame = cv2.flip(frame, 1)  # 水平翻转

    cv2.imshow(“frame”, frame)

saveFile =”imgSave.png”  # 保存文件的路径

    # cv2.imwrite(saveFile, img3, [int(cv2.IMWRITE_PNG_COMPRESSION), 8])  # 保存图像文件, 设置压缩比为8

    cv2.imwrite(saveFile, frame)# 保存图像文件

    frame_to2(frame)

if cv2.waitKey(1) ==ord( q ):break

    #time.sleep(0.1)

    #cv2.waitKey(0);

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
none
暂无评论...