我正在尝试使用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
答案 0 :(得分:1)
正如您所发现的,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']
cx
和cy
是图像质心的x坐标和y坐标。这个版本比使用嵌套循环高出快3000倍。