如何测量物体中心之间的距离 - openCV?

时间:2016-08-06 10:51:40

标签: python-3.x opencv

我有以下代码提取和"跟踪"视频文件或网络摄像头流中的黑色对象。我是Python和CV的新手,我很难理解如何提取被跟踪对象的中心点以进行比较。

代码:

#for this demo the only colour we are interested in is black or near black
#remember open cv uses BGR not RGB
groupColorLower = np.array([0,0,0], dtype = "uint8")
groupColorUpper = np.array([179,179,179], dtype ="uint8")

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", required=True,
    help="path to the input video file")
args = vars(ap.parse_args())

######### Reading input video or opening webcam#########

# if a video path was not supplied, grab the reference
# to the webcam
if not args.get("video", False):
    camera = cv2.VideoCapture(0)

# otherwise, load the video
else:
    camera = cv2.VideoCapture(args["video"])

######### Finished Reading input video or opening webcam#########

# keep looping
while True:

    # grab the current frame
    (grabbed, frame) = camera.read()

    # if we are viewing a video and we did not grab a
    # frame, then we have reached the end of the video
    if args.get("video") and not grabbed:
        break

    # determine which pixels fall within the black boundaries
    # and then blur the binary image 
    blue = cv2.inRange(frame, groupColorLower, groupColorUpper)
    blue = cv2.GaussianBlur(blue, (3, 3), 0)

    # find contours in the image
    (_, contours1, _) = cv2.findContours(blue.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)

    #lets try to sort contours1 left to right
    (contours1, _) = contours.sort_contours(contours1)

    if len(contours1) > 0:
    #now lets extract the center point of the left most contour
        fixedPoint = cv2.moments(contours1[0])
        fixedPointX = int (fixedPoint["m10"] / fixedPoint["m00"])
        fixedPointY = int (fixedPoint["m01"] / fixedPoint["m00"])
        #lets draw a white dot in left most object
        cv2.circle(frame, (fixedPointX, fixedPointY), 7, (255,255,255), -1)

    #lets use the nearest to fixedPoint as anchor (left most [1] where [0] is fixedPoint
    if len(contours1) > 1:
                # sort the contours so we can iterate over them
        cnt2 = sorted([(c, cv2.boundingRect(c)[0]) for c in contours1], key = lambda x: x[1], reverse = True)

        #draw boxes around all objects we are tracking
        for (c, _) in cnt2:
            (x, y, w, h) = cv2.boundingRect(c)

            cv2.rectangle(frame, (x, y), (x + w, y +h), (255, 255, 0), 4)

            M = cv2.moments(c)
            cX = int(M["m10"] / M["m00"])
            cY = int(M["m01"] / M["m00"])
            # draw a dot in center of the black object on the image
            cv2.circle(frame, (cX, cY), 7, (100, 100, 100), -1)
            centre.append((int(M["m10"]/M["m00"]), int(M["m01"]/M["m00"])))

我希望能够在找到对象之间打印距离(以像素为单位),但我不确定如何访问这些数据。

定点计算的工作原理我认为最左边的对象可以是硬编码的,但我需要为任何其他对象找到坐标。

代码当前遍历每个黑色对象并在其中心放置一个点。

感谢您提供的任何帮助:

和j

0 个答案:

没有答案