用cv2抓取本機攝像頭,并且窗口預覽,并用ffmpeg论悴,udp協(xié)議進行推流,延時在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)? # 水平翻轉(zhuǎn)
? ? 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);