gpt4 book ai didi

python - Python:上传图片而不会干扰程序的正常流程

转载 作者:行者123 更新时间:2023-12-02 17:41:18 24 4
gpt4 key购买 nike

在我的代码中,我不断从相机中抓取帧以检查是否存在人体。只要有人,请修剪 body 并将其上传到服务器上。并继续这样做。
问题:每当我启动一个线程将照片上传到服务器时,我的程序就会停止执行并等待上传线程完成。我不想我的程序执行停止并等待。我希望它不停止运行。我想启动一个单独的线程来上传并行运行的照片,在不干扰正常流程的情况下完成其工作,并在完成后进行处理。每次检测到尸体时都应这样做。

# 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()启动它,因为您的过程是连续的,所以您当然没有加入。

  • 简化的代码,因此我可以在最后测试运行它:
    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:请记住线程没有被破坏,并且您必须确保 upload_internet()不会由于任何原因而卡在内存中,或者您可以控制拥有的实例数并设置上限和管理僵尸线程,以避免进程崩溃和错误的内存管理

    关于python - Python:上传图片而不会干扰程序的正常流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44609205/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com