Python:在不干扰程序正常流程的情况下上传图片
在我的代码中,我不断地从摄像机抓取画面,检查是否有人体存在。只要有人,裁剪尸体并上传到服务器上。继续这样做。 问题:每当我启动一个将照片上传到服务器的线程时,我的程序就会停止执行,并等待上传线程完成。我不希望我的程序执行停止并等待。我希望它不停地运行。我想启动一个单独的线程来上传并行运行的照片,在不干扰正常流程的情况下完成它的工作,并在它完成后完成。每次检测到尸体时,它都应该这样做Python:在不干扰程序正常流程的情况下上传图片,python,multithreading,opencv,detection,python-multithreading,Python,Multithreading,Opencv,Detection,Python Multithreading,在我的代码中,我不断地从摄像机抓取画面,检查是否有人体存在。只要有人,裁剪尸体并上传到服务器上。继续这样做。 问题:每当我启动一个将照片上传到服务器的线程时,我的程序就会停止执行,并等待上传线程完成。我不希望我的程序执行停止并等待。我希望它不停地运行。我想启动一个单独的线程来上传并行运行的照片,在不干扰正常流程的情况下完成它的工作,并在它完成后完成。每次检测到尸体时,它都应该这样做 # USAGE # python detect.py --images images # import the n
# USAGE
# python detect.py --images images
# import the necessary packages
from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2
import time
import threading
import Queue
import multiprocessing
import requests
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
from urllib2 import Request, urlopen, URLError
import Queue
import urllib
import traceback
size = 2
i=0
#Queues to store data
queue_FACES = multiprocessing.Queue()
(im_width, im_height) = (112, 112)
# initialize the HOG descriptor/person detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
# Capture Camera Stream
#webcam = cv2.VideoCapture('/home/irum/Desktop/WIN_20170529_09_53_13_Pro.mp4')
webcam = cv2.VideoCapture(0)
#h=4.27 w=4.29 AVG = 4.28
# Upload to server
def upload_internet(filename2,sampleFile,check_path1):
#print("upoading....")
filename2 = filename2+'.jpg'
#print (filename2)
register_openers()
datagen, headers = multipart_encode({"sampleFile": open(sampleFile), "name": filename2})
#request = urllib2.Request("http://videoupload.hopto.org:5000/api/Sync_log", datagen, headers)
request = urllib2.Request("http://videoupload.hopto.org:5002/api/Synclog", datagen, headers)
try:
#print ("***UPLOAD SERVER RESPONSE***")
response = urllib2.urlopen(request)
html=response.read()
print ("html ",html)
#resp = json.loads(html)
# with open('output_file.txt', "wb") as code: #CHANGE PATH
# code.write(curr_time+"\n"+html +"\n")
except URLError , e:
if hasattr(e, 'reason'):
#print ('We failed to reach a server.')
print ('Reason: ', e.reason)
elif hasattr(e, 'code'):
#print ('The server couldn\'t fulfill the request.')
print ('Error code: ', e.code)
except Exception:
print ('generic exception: ' + traceback.format_exc())
while True:
# read each frame
ret, frame = webcam.read()
# resize it
image = imutils.resize(frame, width=min(300, frame.shape[1]))
orig = image.copy()
# detect people in the frame
(rects, weights) = hog.detectMultiScale(image, winStride=(4, 4),
padding=(8, 8), scale=1.05)
# draw the original bounding boxes
for i in range(len(rects)):
body_i = rects[i]
(x, y, w, h) = [v * 1 for v in body_i]
cv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2)
# apply non-maxima suppression
rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)
# draw the final bounding boxes
for i in range(len(rects)):
body_i = rects[i]
(xA, yA, xB, yB) = [int(v * 1) for v in body_i]
# rect on scaled image
cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2)
# rects to map on original frame
(x1, y1, w1, h1) = [int(v * 4.28) for v in body_i]
cv2.rectangle(frame, (x1, y1), (w1, h1), (0, 45, 255), 2)
# Crop body from Original frame
body_big = frame[y1:y1+h1, x1:x1+w1]
# Save body
save_body_path = '/home/irum/Desktop/pedestrian-detection/BIG_BODY'
cur_date = (time.strftime("%Y-%m-%d"))
cur_time = (time.strftime("%H:%M:%S"))
new_pin =cur_date+"-"+cur_time
filename1 = 'BIG'
filename2 = str(filename1)+"-"+str(new_pin)
print ("filename2",filename2)
sampleFile = ('%s/%s.jpg' % (save_body_path, filename2))
print ("sampleFile",sampleFile)
cv2.imwrite('%s/%s.jpg' % (save_body_path, filename2), body_big)
# upload body
upload_process = threading.Thread(target=upload_internet(filename2,sampleFile,save_body_path))
upload_process.start()
# show the output images
cv2.imshow("Before NMS", orig)
cv2.imshow("After NMS", image)
cv2.imshow("BIG BODY", frame)
# cv2.imshow("FACE", body_big2)
key = cv2.waitKey(10)
if key == 27:
break
更正:
使用cThread=threading.Thread target=,args=定义
新线程实例
使用cThread.start启动它,当然您没有join,因为您的进程是连续的。
简化的代码,以便我可以在我的终端测试运行它:
import time
import threading
import multiprocessing
from time import sleep
def upload_internet(filename,sampleFile,check_path):
print ("//// WAITING FOR SERVER RESPONSE")
time.sleep(3)
print ("RECEIVED SERVER RESPONSE \\\\\\")
filename = "filename"
sampleFile = "sampleFile"
save_body_path = "save_body_path"
key = 1
while True:
rects = range(0,10)
# draw the original bounding boxes
range_len_rects = range(len(rects))
for i in range_len_rects:
print("Main starts")
rects = range(0,10)
thread_list = []
for i in range_len_rects:
# upload body
thread_list.append ( threading.Thread( target=upload_internet, args=( filename + "-" + str(i) ,sampleFile,save_body_path) ) )
thread_list[i].start()
print ("Exiting Launch Thread loop :"+ str(i) + "/" + str(range_len_rects[i]) )
print("Main sleep for 10 seconds")
time.sleep(10);
if key == 27:
break
PS:请记住线程没有被破坏,您必须确保上载internet不会因为任何原因卡在内存中,或者您可以控制您拥有的实例数量,设置cap并管理僵尸线程,以避免进程崩溃和内存管理错误谢谢!这很有帮助。还有一件事,因为我是python新手。如果我需要再运行两个线程,一个像upload线程,另一个我需要等待线程返回的结果,然后对返回的值执行进一步的操作。我将如何实现这个线程类?首先,如果消息是正确的答案,您应该将其标记为答案,并且在我的回复旁边将有绿色复选框。您可以使用队列的put和get来准备父线程,并等待回复,我个人更喜欢将管道与多处理结合使用,因为我会将其作为一个答案,但我的问题保持不变。但它仍然很有用,因为我是python新手,对线程不太了解。我希望你不介意:p