所以我正在制作一个Flask应用程序,它可以打开和关闭树莓派中的相机。服务器代码如图所示:
from flask import Flask, request, Response
import requests, json, ast
import cv2, time, pandas
import threading
# importing datetime class from datetime library
from datetime import datetime
app = Flask(__name__)
@app.route('/', methods=['POST'])
def camera():
from camera_opencv_class import videoCapture
data=list(request.form.keys())[0]
print(data)
if data=="turnon":
video_object=videoCapture()
t_videoCapture=threading.Thread(target=video_object.show)
t_videoCapture.start()
for i in threading.enumerate():
i.record=True
return Response(status=200)
elif data=="turnoff":
for i in threading.enumerate():
i.record=False
return Response(status=200)
return Response(status=200)
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True,port=8000)
并显示camera_opencv_class代码:
import cv2
from datetime import datetime
import threading
class videoCapture:
# Capturing video
def show(placeholder):
video = cv2.VideoCapture(0)
# Assigning our static_back to None
static_back = None
# List when any moving object appear
motion_list = [ None, None ]
videoCapture_thread=threading.currentThread()
while getattr(videoCapture_thread,"record",True):
# Reading frame(image) from video
check, frame = video.read()
# Initializing motion = 0(no motion)
motion = 0
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray=cv2.GaussianBlur(gray,(21,21),0)
if static_back is None:
static_back=gray
continue
diff_frame=cv2.absdiff(static_back,gray)
thresh_frame=cv2.threshold(diff_frame,30,255,cv2.THRESH_BINARY)[1]
thresh_frame=cv2.dilate(thresh_frame,None,iterations=2)
(cnts,_)=cv2.findContours(thresh_frame.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for contour in cnts:
if cv2.contourArea(contour)<10000:
continue
motion=1
(x,y,w,h)=cv2.boundingRect(contour)
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),3)
# Displaying image in gray_scale
#cv2.imshow("Gray Frame", gray)
# Displaying the difference in currentframe to
# the staticframe(very first_frame)
#cv2.imshow("Difference Frame", diff_frame)
# Displaying the black and white image in which if
# intencity difference greater than 30 it will appear white
#cv2.imshow("Threshold Frame", thresh_frame)
# Displaying color frame with contour of motion of object
cv2.imshow("Color Frame", frame)
key = cv2.waitKey(1)
#print("on")
video.release()
# Destroying all the windows
cv2.destroyAllWindows()
正如你所看到的,当我发送打开相机的请求时,线程将开始打开相机,而当我发送关闭相机的请求后,线程的";记录";属性将为False,因此线程将结束。这是有效的。然而,当我再次发送开机请求时,创建了一个新线程,但什么也没发生;相机没有打开。有人知道为什么吗?也许是openCV中的一些独特之处不允许我这样做?或者有人知道更好的方法来完成这项任务吗?服务器是使用Ngrok转发的,我使用一台单独的计算机进行请求(主要目标是使用我手机上的IFTTT(
添加
t_video_capture.join()
然后返回响应。