gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:50:12 25 4
gpt4 key购买 nike

我正在尝试使用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倍。

关于python - 质心计算程序中的时间滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23911434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com