Live streaming with Python

mind_ programmonkey 2020-11-13 04:19:44
live streaming python


Python Realize streaming live

First of all, we will show the results , Generally, it is to check whether the industrial board appears . The method of detection is simple , With OpenCV Template detection .
 Insert picture description here

General train of thought

  • opencv Read video
  • Split the video into frames
  • Process every frame (opencv Template matching )
  • Write this frame to pipe The Conduit
  • utilize ffmpeg Live streaming

Problems encountered in the middle

When dealing with local video , There's no case of the delayed jamming . But for real-time video streaming , There's a Caton delay effect . After a meal of douniang's operation , Take a multi-threaded approach .

opencv Read video

def run_opencv_camera():
video_stream_path = 0
# When video_stream_path = 0 Will turn on the computer Default camera It can also be the path of the local video file 
cap = cv2.VideoCapture(video_stream_path)
while cap.isOpened():
is_opened, frame = cap.read()
cv2.imshow('frame', frame)
cv2.waitKey(1)
cap.release()

OpenCV Template matching

Template matching is one of the ways to find a specific target in an image , The principle of this method is very simple , Traverse every possible position in the image , Compare the similarity between each part and the template , When the similarity is high enough , Think you've found the target .

def template_match(img_rgb):
# Gray scale conversion 
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# Template matching 
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
# Set the threshold 
threshold = 0.8
loc = np.where(res >= threshold)
if len(loc[0]):
# This is a direct fixed area 
cv2.rectangle(img_rgb, (155, 515), (1810, 820), (0, 0, 255), 3)
cv2.putText(img_rgb, category, (240, 600), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img_rgb, Confidence, (240, 640), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img_rgb, Precision, (240, 680), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img_rgb, product_yield, (240, 720), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img_rgb, result, (240, 780), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 5)
return img_rgb

FFmpeg Push flow

  • stay Ubuntu 14 Installation on Nginx-RTMP Streaming media server
    https://www.cnblogs.com/cocoajin/p/4353767.html
import subprocess as sp
rtmpUrl = ""
camera_path = ""
cap = cv.VideoCapture(camera_path)
# Get video information
fps = int(cap.get(cv.CAP_PROP_FPS))
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
# ffmpeg command
command = ['ffmpeg',
'-y',
'-f', 'rawvideo',
'-vcodec','rawvideo',
'-pix_fmt', 'bgr24',
'-s', "{}x{}".format(width, height),
'-r', str(fps),
'-i', '-',
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
'-preset', 'ultrafast',
'-f', 'flv',
rtmpUrl]
# Piping configuration 
p = sp.Popen(command, stdin=sp.PIPE)
# read webcamera
while(cap.isOpened()):
ret, frame = cap.read()
if not ret:
print("Opening camera is failed")
break
# process frame
# your code
# process frame
# write to pipe
p.stdin.write(frame.tostring())
  • explain :rtmp It's the server that accepts the video , The server can follow the connection address given above .

Multithreading

  • python mutilprocessing Multiprocess programming https://blog.csdn.net/jeffery0207/article/details/82958520
def image_put(q):
# Take local video verification 
cap = cv2.VideoCapture("./new.mp4")
# Take the form of video streaming 
# cap = cv2.VideoCapture(0)
# cap.set(cv2.CAP_PROP_FRAME_WIDTH,1920)
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT,1080)
if cap.isOpened():
print('success')
else:
print('faild')
while True:
q.put(cap.read()[1])
q.get() if q.qsize() > 1 else time.sleep(0.01)
def image_get(q):
while True:
# start = time.time()
#flag += 1
frame = q.get()
frame = template_match(frame)
# end = time.time()
# print("the time is", end-start)
cv2.imshow("frame", frame)
cv2.waitKey(0)
# pipe.stdin.write(frame.tostring())
#cv2.imwrite(save_path + "%d.jpg"%flag,frame)
# Multithreaded execution of a camera 
def run_single_camera():
# initialization 
mp.set_start_method(method='spawn') # init
# queue 
queue = mp.Queue(maxsize=2)
processes = [mp.Process(target=image_put, args=(queue, )),
mp.Process(target=image_get, args=(queue, ))]
[process.start() for process in processes]
[process.join() for process in processes]
def run():
run_single_camera() # quick, with 2 threads
pass
  • explain : Use Python3 The multithread module comes with mutilprocessing modular , Create a queue , Threads A From pass rstp The protocol reads every frame from the video stream , And put it in the queue , Threads B Take the picture out of the queue , Display after processing . Threads A If you find two pictures in the queue , Threads B Can't keep up with the thread's reading speed A, So thread A Take the initiative to delete the old pictures in the queue , Change the picture .

Full code display

import time
import multiprocessing as mp
import numpy as np
import random
import subprocess as sp
import cv2
import os
# Definition opencv Template required 
template_path = "./high_img_template.jpg"
# Define the variables to be displayed by the rectangular box 
category = "Category: board"
var_confidence = (np.random.randint(86, 98)) / 100
Confidence = "Confidence: " + str(var_confidence)
var_precision = round(random.uniform(98, 99), 2)
Precision = "Precision: " + str(var_precision) + "%"
product_yield = "Product Yield: 100%"
result = "Result: perfect"
# Read the template and get the height and width of the template 
template = cv2.imread(template_path, 0)
h, w = template.shape[:2]
# Define template matching functions 
def template_match(img_rgb):
# Gray scale conversion 
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# Template matching 
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
# Set the threshold 
threshold = 0.8
loc = np.where(res >= threshold)
if len(loc[0]):
# This is a direct fixed area 
cv2.rectangle(img_rgb, (155, 515), (1810, 820), (0, 0, 255), 3)
cv2.putText(img_rgb, category, (240, 600), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img_rgb, Confidence, (240, 640), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img_rgb, Precision, (240, 680), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img_rgb, product_yield, (240, 720), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img_rgb, result, (240, 780), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 5)
return img_rgb
# Video properties 
size = (1920, 1080)
sizeStr = str(size[0]) + 'x' + str(size[1])
# fps = cap.get(cv2.CAP_PROP_FPS) # 30p/self
# fps = int(fps)
fps = 11
hz = int(1000.0 / fps)
print ('size:'+ sizeStr + ' fps:' + str(fps) + ' hz:' + str(hz))
rtmpUrl = 'rtmp://localhost/hls/test'
# Live channel output 
# ffmpeg push rtmp a key : Through pipes How to share data 
command = ['ffmpeg',
'-y',
'-f', 'rawvideo',
'-vcodec','rawvideo',
'-pix_fmt', 'bgr24',
'-s', sizeStr,
'-r', str(fps),
'-i', '-',
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
'-preset', 'ultrafast',
'-f', 'flv',
rtmpUrl]
# Pipeline characteristic configuration 
# pipe = sp.Popen(command, stdout = sp.PIPE, bufsize=10**8)
pipe = sp.Popen(command, stdin=sp.PIPE) #,shell=False
# pipe.stdin.write(frame.tostring())
def image_put(q):
# Take local video verification 
cap = cv2.VideoCapture("./new.mp4")
# Take the form of video streaming 
# cap = cv2.VideoCapture(0)
# cap.set(cv2.CAP_PROP_FRAME_WIDTH,1920)
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT,1080)
if cap.isOpened():
print('success')
else:
print('faild')
while True:
q.put(cap.read()[1])
q.get() if q.qsize() > 1 else time.sleep(0.01)
# Take the way of local video to save pictures 
save_path = "./res_imgs"
if os.path.exists(save_path):
os.makedir(save_path)
def image_get(q):
while True:
# start = time.time()
#flag += 1
frame = q.get()
frame = template_match(frame)
# end = time.time()
# print("the time is", end-start)
cv2.imshow("frame", frame)
cv2.waitKey(0)
# pipe.stdin.write(frame.tostring())
#cv2.imwrite(save_path + "%d.jpg"%flag,frame)
# Multithreaded execution of a camera 
def run_single_camera():
# initialization 
mp.set_start_method(method='spawn') # init
# queue 
queue = mp.Queue(maxsize=2)
processes = [mp.Process(target=image_put, args=(queue, )),
mp.Process(target=image_get, args=(queue, ))]
[process.start() for process in processes]
[process.join() for process in processes]
def run():
run_single_camera() # quick, with 2 threads
pass
if __name__ == '__main__':
run()

Reference article

    1. stay Ubuntu 14 Installation on Nginx-RTMP Streaming media server :https://www.cnblogs.com/cocoajin/p/4353767.html
    1. python mutilprocessing Multiprocess programming :https://blog.csdn.net/jeffery0207/article/details/82958520
    1. ffmpeg Convert video and pictures to each other :https://blog.csdn.net/TingiBanDeQu/article/details/53896944
    1. be based on python2.7 Of opencv3.3-ffmpeg-rtmp Video processing and streaming :https://blog.csdn.net/u014303844/article/details/80394101
    1. Read multiple ( The sea, \ Dahua ) Webcam video stream ( Use opencv-python), Solve the real-time read delay problem :https://zhuanlan.zhihu.com/p/38136322
    1. python utilize ffmpeg Conduct rtmp Push the live streaming :https://zhuanlan.zhihu.com/p/74260950
版权声明
本文为[mind_ programmonkey]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database