质心计算程序中的时滞问题

2024-03-29 05:41:30 发布

您现在位置: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

Tags: andoftheimagenpchannelgreenblue
1条回答
网友
1楼 · 发布于 2024-03-29 05:41:30

正如您所发现的,Python中的嵌套循环是very slow。最好避免使用嵌套循环迭代每个像素。幸运的是,OpenCV有一些内置函数,它们完全可以实现您想要实现的功能:^{},用于创建位于指定边界之间的像素的二值图像;和^{},用于计算二值图像的质心。我强烈建议您阅读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倍。你知道吗

相关问题 更多 >