0

私のコードでは、人体が存在するかどうかを確認するためにカメラからフレームを常に取得しています。人間がいるときはいつでも、体を切り取ってサーバーにアップロードしてください。これを続けてください。 問題:写真をサーバーにアップロードするスレッドを開始するたびに、プログラムの実行が停止し、アップロードスレッドが終了するのを待ちます。私はプログラムの実行を止めて待たずにいたい。私はそれを止めることなく走りたい。私は、平行して走っている写真をアップロードする別のスレッドを開始し、通常の流れを乱すことなくその仕事をし、その後に終了したい。身体が検出されるたびにこれを行う必要があります。Python:プログラムの通常の流れを乱すことなく画像をアップロード

# 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 

答えて

1

訂正:

  1. 使用cThread = threading.Thread(target= , args=())、それを起動するために使用cThread.start()
  2. 新しいスレッドのインスタンスを定義するには、もちろん、あなたのプロセスが連続しているので、参加していません。

簡略化されたコードは、私は私の最後でそれを実行しテストすることができ :

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()が何らかの理由でメモリ内に立ち往生していないことを確認しなければなりません、またはインスタンスの数を制御して上限を設定し、ゾンビスレッドを管理して、プロセスクラッシュや悪いメモリ管理を避けることができます

+0

ありがとう!非常に役に立ちます。私がPythonを初めて使ったときのもう一つのこと。スレッドを2つ以上アップロードする必要がある場合、スレッドによって返された結果を待つ必要がある場合は、戻り値をさらに実行します。どのように私はこのスレッドクラスを実装するだろうか? –

+0

まず、メッセージが正しい答えであれば、それを「回答」とタグ付けし、返信の隣に緑色のチェックボックスが表示されます。 –

+0

'queue'の' put() 'と' get() 'を使って親スレッドを待ち受けて応答を待つことができます。https://docs.python.org/2/library/queue.html、私個人的には、その目的のために 'pipe()'と 'multiprocessing'を使います。 https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Pipe –

関連する問題