python - 质心计算程序中的时间滞后

我正在尝试使用OpenCV和Python确定一个特定对象的质心。
我正在使用以下代码,但是计算质心花费了太多时间。
为此,我需要一种更快的方法-是否应该更改摄像机的分辨率以提高计算速度?
这是我的代码:

meanI=[0]
meanJ=[0]

#taking infinite frames continuously to make a video
while(True):
    ret, frame = capture.read()
    rgb_image = cv2.cvtColor(frame , 0)
    content_red = rgb_image[:,:,2] #red channel of image
    content_green = rgb_image[:,:,1] #green channel of image
    content_blue = rgb_image[:,:,0] #blue channel of image
    r = rgb_image.shape[0] #gives the rows of the image matrix
    c = rgb_image.shape[1] # gives the columns of the image matrix
    d = rgb_image.shape[2] #gives the depth order of the image matrux
    binary_image = np.zeros((r,c),np.float32)
    for i in range (1,r):  #thresholding the object as per requirements
        for j in range (1,c):
            if((content_red[i][j]>186) and (content_red[i][j]<230) and \
               (content_green[i][j]>155) and (content_green[i][j]<165) and \
               (content_blue[i][j]> 175) and (content_blue[i][j]< 195)):
                binary_image[i][j] = 1
                meanI.append(i)
                meanJ.append(j)

    cv2.imshow('frame1',binary_image)
    cv2.waitKey()
    cox = np.mean(meanI) #x-coordinate of centroid
    coy = np.mean(meanJ) #y-coordinate of centroid

最佳答案

您已经发现,Python中的嵌套循环是very slow。最好避免使用嵌套循环遍历每个像素。幸运的是,OpenCV具有一些内置功能,这些功能完全可以实现您想要实现的功能: inRange()moments() (可创建位于指定范围之间的像素的二进制图像),可用于计算二进制的质心图片。我强烈建议阅读OpenCV的documentation,以了解该库提供的内容。

结合这两个功能,可以得到以下代码:

import numpy as np
import cv2

lower = np.array([175, 155, 186], np.uint8) # Note these ranges are BGR ordered
upper = np.array([195, 165, 230], np.uint8)
binary = cv2.inRange(im, lower, upper) # im is your BGR image
moments = cv2.moments(binary, True)
cx = moments['m10'] / moments['m00']
cy = moments['m01'] / moments['m00']
cxcy是图像质心的x和y坐标。这个版本的高达,比使用嵌套循环快3000倍。

https://stackoverflow.com/questions/23911434/

相关文章:

python - 使用OpenCV计数视频中的帧…(Python)

opencv - ANN-人工神经网络训练

macos - 带有OpenCV Mac的CMake(小牛)

docker - 无法在 Dockerfile 中运行 sysctl 命令

python - 使用 slider 编辑颜色值

docker - depends_on不等待docker-compose 1.22.0中的其他服务

android - 如何使用静态OpenCV在Android中使用JavaCV的静态方法

opencv - OpenCV直方图反投影替代

android - 使用JNI获取arrayList的元素

opencv - 如何从opencv中的上下文获取设备列表