当对象周围的矩形包含点时如何保存和打印objectID

时间:2018-10-20 08:18:22

标签: python-3.x opencv3.3

我是python的新手,它以不同的方式进行学习。下面的代码用于使用从 pyimagesearch 提取的caffe模型进行人脸跟踪。我不是深度学习,只是想从中学习技巧。代码运行良好,并为检测到的面部分配了ID。当周围的矩形包含任何点时,我添加了一些额外的行来打印检测到的面部的ID当检测到一张脸时,它的ID打印得很好,但是在多个矩形上却没有。

任何想法都会有所帮助。

代码:

# USAGE
# python object_tracker.py --prototxt deploy.prototxt --model res10_300x300_ssd_iter_140000.caffemodel

# import the necessary packages
from pyimagesearch.centroidtracker import CentroidTracker
from imutils.video import VideoStream
from mouseclick import MouseClick
import numpy as np
import argparse
import imutils
import time
import cv2

# construct the argument parse and parse the arguments
#ap = argparse.ArgumentParser()
#ap.add_argument("-p", "--prototxt", required=True,
#   help="path to Caffe 'deploy' prototxt file")
#ap.add_argument("-m", "--model", required=True,
#   help="path to Caffe pre-trained model")
#ap.add_argument("-c", "--confidence", type=float, default=0.7,
#   help="minimum probability to filter weak detections")
#args = vars(ap.parse_args())

# initialize our centroid tracker and frame dimensions
ct = CentroidTracker()
(H,W) = (None,None)
confidence = 0.5

windowName = "Frame"
cv2.namedWindow(windowName)
mc = MouseClick()
cv2.setMouseCallback(windowName,mc.MouseClick)

net = cv2.dnn.readNetFromCaffe("deploy.prototxt","res10_300x300_ssd_iter_140000.caffemodel")
vs = VideoStream(src=0).start()
time.sleep(1.0)

ct = CentroidTracker()

def containTest(rect,mousePt):
    logic = rect[0] < mousePt[0] < rect[0]+rect[2] and rect[1] < mousePt[1] < rect[1]+rect[3]
    return logic

while True:
    frame = vs.read()
    frame = imutils.resize(frame,width=400)

    if W is None or H is None:
        (H,W) = frame.shape[:2]

    blob = cv2.dnn.blobFromImage(frame,1.0,(W,H),(104.0,177.0,123.0))
    net.setInput(blob)
    detections = net.forward()
    rects = []

    for i in range(0, detections.shape[2]):
        if detections[0,0,i,2] > confidence:
            box = detections[0,0,i,3:7] * np.array([W,H,W,H])
            rects.append(box.astype("int"))

            (startX,startY,endX,endY) = box.astype("int")
            cv2.rectangle(frame,(startX,startY),(endX,endY),(0,0,255),2)

    objects = ct.update(rects)

    for (objectID, centroid) in objects.items():
        text = "ID {}".format(objectID)
        cv2.putText(frame,text,(centroid[0]-10,centroid[1]-10),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),2)
        cv2.circle(frame,(centroid[0],centroid[1]),4,(0,0,255),-1)


        if mc.left_button_clicked:
            inTest = containTest(rects[objectID],mc.position)
            if inTest:
                print(objectID)
        mc.new_iteration()

    cv2.imshow(windowName,frame)
    key = cv2.waitKey(10) & 0xFF
    if key == 27:
        break

cv2.destroyAllWindows()
vs.stop()

0 个答案:

没有答案