矩在每个轮廓上传递,但每次圆都无法到达矩形中心的预测位置时;每次(0,0)都不是我想要的中心时,该位置是恒定的

结果是(0,0)处的白色圆圈

# -*- coding: utf-8 -*-
"""
Created on Sat Apr  6 09:53:56 2019

@author: lenovo
"""

import cv2
import numpy as np
import time

lowerBound=np.array([85,153,50])
upperBound=np.array([255,255,255])
cam= cv2.VideoCapture(1)

kernelOpen=np.ones((5,5))
kernelClose=np.ones((20,20))

font = cv2.FONT_HERSHEY_SIMPLEX
while True:
    ret, img=cam.read()
    img=cv2.resize(img,(340,220))

    #convert BGR to HSV
    imgHSV= cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    # create the Mask
    mask=cv2.inRange(imgHSV,lowerBound,upperBound)
    #morphology
    maskOpen=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernelOpen)
    maskClose=cv2.morphologyEx(maskOpen,cv2.MORPH_CLOSE,kernelClose)

    maskFinal=maskClose
    _,conts,h=cv2.findContours(maskFinal.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

    cv2.drawContours(img,conts,-1,(255,0,0),3)

    for i in range(len(conts)):
        M = cv2.moments(i)
        x,y,w,h=cv2.boundingRect(conts[i])
        if M["m00"] != 0:

            cX = int(M["m10"] / M["m00"])
            cY = int(M["m01"] / M["m00"])
        else:

    # set values as what you need in the situation
            cX, cY = 0, 0
        cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255), 2)
        cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1)
        cv2.putText(img, str(i+1),(x,y+h),cv2.FONT_HERSHEY_SIMPLEX,1.0,(0,255,255))


    cv2.imshow("maskClose",maskClose)
    cv2.imshow("maskOpen",maskOpen)
    cv2.imshow("mask",mask)
    cv2.imshow("cam",img)
    cv2.waitKey(10)

最佳答案

M = cv2.moments(i)应该是M = cv2.moments(conts[i]),当前您正在输入索引,而不是轮廓。

您所计算的是轮廓的质心,该质心可能与边界矩形的中心不同。例:
python - 瞬间帮助python opencv检测-LMLPHP

如果要在边界矩形的中心处有一个圆,则应使用x,y,w,h尺寸进行计算:

cX = x + int(w/2)
cY = y + int(h/2)

08-25 10:56