基于Linux、Win、OpenCV、树莓派、OpenMV、MicroPython等大部分开发环境的网络摄像头图像输出(将本地摄像头转为网络,可进行人脸检测)
文章目录
- 图像输出
- 附录:列表的赋值类型和py打包
- 列表赋值
- BUG复现
- 代码改进
- 优化
- 总结
- py打包
图像输出
开发环境中得有Python环境 Python环境自带Flask库
另外需要采集内置摄像头图像 这里用的为OpenCV库实现 同样也可以用picamera等可以调用摄像头的库 或者直接从底层调用摄像头驱动
开发环境中可以配置多进程开机自动运行 使其在调用的同时也可以进行其他工作
在代码上可以增加控制功能 包括系统开关等 可扩展性高
以Linux环境为例 配置开机自动运行的脚本为:
[Desktop Entry]
Name=dotnet
Comment=dotnet Program
Exec=lxterminal -e sudo python3 /home/pi/Desktop/Test/Track_All_1.0.py
Terminal=True
MultipleArgs=false
Type=Application
Categories=Application;Development;
StartupNotify=true
首先建立服务器,同时用OpenCV调用本地摄像头采集图像 并转为比特格式
代码如下:
from flask import Flask,Response
import cv2
local_post = 1212
app = Flask(__name__)
cap = cv2.VideoCapture(0) # 开启摄像头
def send_img():
while True:
ok, faceImg = cap.read() # 读取摄像头图像
if ok is False:
break
image = cv2.imencode('.jpg', faceImg)[1].tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + image + b'\r\n')
return
@app.route('/video_feed')
def video_feed():
return Response(send_img(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/')
def hello():
return 'Hello World!'
if __name__ == "__main__":
app.run(host='0.0.0.0', port=local_post)
服务器建立好后 IP地址+端口1212+video_feed地址下则为图像视频流
如192.168.1.1:1212/video_feed/
若需要进行网络控制 则新建一个HTLM文件 如index.html
输入HTLM语言程序:
<html>
<head>
<title>局域网视频推流及控制系统</title>
</head>
<body>
<h1>局域网视频推流及控制系统</h1>
<form action="/" method="post" style="float:left">
<p>
<input type="submit" style="font-size:60px" name="auto" value="自动模式">
<input type="submit" style="font-size:60px" name="manu" value="手动模式">
</p>
<p>
<input type="submit" style="font-size:60px" name="reset" value="复位导轨">
<input type="submit" style="font-size:60px" name="set" value="设置点位">
</p>
<p>
<input type="submit" style="font-size:60px" name="left" value="左移导轨">
<input type="submit" style="font-size:60px" name="right" value="右移导轨">
</p>
<p>
<input type="submit" style="font-size:60px" name="go_in" value="继续程序">
<input type="submit" style="font-size:60px" name="go_out" value="暂停程序">
</p>
<p>
<input type="submit" style="font-size:60px" name="stop" value="停止导轨">
<input type="submit" style="font-size:60px" name="quit" value="全部退出">
</p>
</form>
<img src="{{ url_for('video_feed') }}" height="520" style="float:left">
</body>
</html>
打开IP地址+端口号即可看到实时图像并进行网络控制
用多线程函数加入人脸识别及网络控制的改进效果即:
import cv2
from flask import Flask, render_template, Response, request
import threading
import socket
#import tkinter as tk
local_ip = str(socket.gethostbyname(socket.gethostname()))
local_post = 1212
app = Flask(__name__)
cap = cv2.VideoCapture(0) # 开启摄像头
classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
@app.route('/', methods=['GET', 'POST'])
def index():
global command_str
command_str = None
if request.method == 'POST':
c0 = str(request.form.get('change'))
c1 = str(request.form.get('quit'))
c2 = str(request.form.get('left'))
c3 = str(request.form.get('right'))
c4 = str(request.form.get('stop'))
c5 = str(request.form.get('reset'))
c6 = str(request.form.get('set'))
print(c0,c1,c2,c3,c4,c5,c6)
for i in [c0,c1,c2,c3,c4,c5,c6]:
if i != "None":
command_str = i
break
print(command_str)
return render_template('index.html')
def track():
global faceImg
global q
global command_str
command_str = None
q = 0
while True:
ok, faceImg = cap.read() # 读取摄像头图像
faceImg = cv2.flip(faceImg,1)
if ok is False:
print('无法读取到摄像头!')
break
gray = cv2.cvtColor(faceImg,cv2.COLOR_BGR2GRAY)
faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))
if len(faceRects):
for faceRect in faceRects:
x,y,w,h = faceRect
# 框选出人脸 最后一个参数2是框线宽度
cv2.rectangle(faceImg,(x, y), (x + w, y + h), (0,255,0), 2)
cv2.imshow("http://"+local_ip+":"+str(local_post)+"/ (img: video_feed)",faceImg)
# 展示图像
if command_str == "复位":
print("Reset")
elif command_str == "标定":
print("Set")
elif command_str == "切换":
print("Change")
elif command_str == "左移":
print("Left")
elif command_str == "右移":
print("Right")
elif command_str == "停止":
print("Stop")
else:
command_str = command_str
if cv2.waitKey(10) == 27 or command_str == "退出": # 通过esc键退出摄像
command_str = None
print("Quit")
break
command_str = None
cap.release()
cv2.destroyAllWindows()
q = 1
def send_img():
global faceImg
global q
q = 0
while True:
image = cv2.imencode('.jpg', faceImg)[1].tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + image + b'\r\n')
if q==1:
break
return
@app.route('/video_feed')
def video_feed():
return Response(send_img(), mimetype='multipart/x-mixed-replace; boundary=frame')
def start_server():
app.run(host='0.0.0.0', port=local_post)
#def central_win(win):
# win.resizable(0,0) # 不可缩放
# screenwidth = win.winfo_screenwidth() # 获取屏幕分辨率宽
# screenheight = win.winfo_screenheight() # 获取屏幕分辨率高
# win.update() # 更新窗口
# width = win.winfo_width() # 重新赋值
# height = win.winfo_height()
# size = '+%d+%d' % ((screenwidth - width)/2, (screenheight - height)/2)
# # 重新赋值大小 大小为屏幕大小/2
# win.geometry(size) # 以新大小定义窗口
#
#def info_win(str_list):
# info=tk.Tk()
# info.title("小提示")
# info.attributes('-topmost',1)
# infofram=tk.Frame(info,width=320, height=260)
# infofram.grid_propagate(0)
# infofram.grid()
# central_win(info)
#
# labelName=tk.Label(info, text=str_list, justify=tk.LEFT)
# labelName.place(x=10, y=20, width=300, height=160)
#
# def go_info():
# info.destroy()
#
# tk.Button(infofram,width=30,text="确定",command=go_info).place(x=10, y=200, width=300, height=40)
#
# info.mainloop()
# return
#def ip_win():
# info_win("本机IP地址为:"+local_ip)
#thread_win = threading.Thread(target=ip_win)
#thread_win.setDaemon(True)
#thread_win.start()
thread_img = threading.Thread(target=track)
thread_img.setDaemon(True)
thread_img.start()
thread_send = threading.Thread(target=start_server)
thread_send.setDaemon(True)
thread_send.start()
附录:列表的赋值类型和py打包
列表赋值
BUG复现
闲来无事写了个小程序 代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021
@author: 16016
"""
a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
for j in range(16):
a_list[j]=str(a_list[j])+'_'+str(j)
print("序号:",j)
print('a_list:\n',a_list)
c_list[j]=a_list
print('c_list[0]:\n',c_list[0])
print('\n')
# b_list[j]=a_list[7],a_list[8]
# print(b_list[j])
# 写入到Excel:
#print(c_list,'\n')
我在程序中 做了一个16次的for循环 把列表a的每个值后面依次加上"_"和循环序号
比如循环第x次 就是把第x位加上_x 这一位变成x_x 我在输出测试中 列表a的每一次输出也是对的
循环16次后列表a应该变成[‘0_0’, ‘1_1’, ‘2_2’, ‘3_3’, ‘4_4’, ‘5_5’, ‘6_6’, ‘7_7’, ‘8_8’, ‘9_9’, ‘10_10’, ‘11_11’, ‘12_12’, ‘13_13’, ‘14_14’, ‘15_15’] 这也是对的
同时 我将每一次循环时列表a的值 写入到空列表c中 比如第x次循环 就是把更改以后的列表a的值 写入到列表c的第x位
第0次循环后 c[0]的值应该是[‘0_0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’, ‘11’, ‘12’, ‘13’, ‘14’, ‘15’] 这也是对的
但是在第1次循环以后 c[0]的值就一直在变 变成了c[x]的值
相当于把c_list[0]变成了c_list[1]…以此类推 最后得出的列表c的值也是每一项完全一样
我不明白这是怎么回事
我的c[0]只在第0次循环时被赋值了 但是后面它的值跟着在改变
如图:
第一次老出bug 赋值以后 每次循环都改变c[0]的值 搞了半天都没搞出来
无论是用appen函数添加 还是用二维数组定义 或者增加第三个空数组来过渡 都无法解决
代码改进
后来在我华科同学的指导下 突然想到赋值可以赋的是个地址 地址里面的值一直变化 导致赋值也一直变化 于是用第二张图的循环套循环深度复制实现了
代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021
@author: 16016
"""
a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
for j in range(16):
a_list[j]=str(a_list[j])+'_'+str(j)
print("序号:",j)
print('a_list:\n',a_list)
for i in range(16):
c_list[j].append(a_list[i])
print('c_list[0]:\n',c_list[0])
print('\n')
# b_list[j]=a_list[7],a_list[8]
# print(b_list[j])
# 写入到Excel:
print(c_list,'\n')
解决了问题
优化
第三次是请教了老师 用copy函数来赋真值
代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021
@author: 16016
"""
a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
for j in range(16):
a_list[j]=str(a_list[j])+'_'+str(j)
print("序号:",j)
print('a_list:\n',a_list)
c_list[j]=a_list.copy()
print('c_list[0]:\n',c_list[0])
print('\n')
# b_list[j]=a_list[7],a_list[8]
# print(b_list[j])
# 写入到Excel:
#print(c_list,'\n')
同样能解决问题
最后得出问题 就是指针惹的祸!
a_list指向的是个地址 而不是值 a_list[i]指向的才是单个的值 copy()函数也是复制值而不是地址
如果这个用C语言来写 就直观一些了 难怪C语言是基础 光学Python不学C 遇到这样的问题就解决不了
C语言yyds Python是什么垃圾弱智语言
总结
由于Python无法单独定义一个值为指针或者独立的值 所以只能用列表来传送
只要赋值是指向一个列表整体的 那么就是指向的一个指针内存地址 解决方法只有一个 那就是将每个值深度复制赋值(子列表内的元素提取出来重新依次连接) 或者用copy函数单独赋值
如图测试:
部分代码:
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 16:45:48 2021
@author: 16016
"""
def text1():
A=[1,2,3]
B=[[],[],[]]
for i in range(len(A)):
A[i]=A[i]+i
B[i]=A
print(B)
def text2():
A=[1,2,3]
B=[[],[],[]]
A[0]=A[0]+0
B[0]=A
print(B)
A[1]=A[1]+1
B[1]=A
print(B)
A[2]=A[2]+2
B[2]=A
print(B)
if __name__ == '__main__':
text1()
print('\n')
text2()
py打包
Pyinstaller打包exe(包括打包资源文件 绝不出错版)
依赖包及其对应的版本号
PyQt5 5.10.1
PyQt5-Qt5 5.15.2
PyQt5-sip 12.9.0
pyinstaller 4.5.1
pyinstaller-hooks-contrib 2021.3
Pyinstaller -F setup.py 打包exe
Pyinstaller -F -w setup.py 不带控制台的打包
Pyinstaller -F -i xx.ico setup.py 打包指定exe图标打包
打包exe参数说明:
-F:打包后只生成单个exe格式文件;
-D:默认选项,创建一个目录,包含exe文件以及大量依赖文件;
-c:默认选项,使用控制台(就是类似cmd的黑框);
-w:不使用控制台;
-p:添加搜索路径,让其找到对应的库;
-i:改变生成程序的icon图标。
如果要打包资源文件
则需要对代码中的路径进行转换处理
另外要注意的是 如果要打包资源文件 则py程序里面的路径要从./xxx/yy换成xxx/yy 并且进行路径转换
但如果不打包资源文件的话 最好路径还是用作./xxx/yy 并且不进行路径转换
def get_resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
而后再spec文件中的datas部分加入目录
如:
a = Analysis(['cxk.py'],
pathex=['D:\\Python Test\\cxk'],
binaries=[],
datas=[('root','root')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
而后直接Pyinstaller -F setup.spec即可
如果打包的文件过大则更改spec文件中的excludes 把不需要的库写进去(但是已经在环境中安装了的)就行
这些不要了的库在上一次编译时的shell里面输出
比如:
然后用pyinstaller --clean -F 某某.spec