【发布时间】:2019-09-11 03:54:09
【问题描述】:
在过去的几天里,我一直在碰壁,试图优化我的代码以提高速度。然而,这里的这段代码仍然很慢,我不太确定如何具体提高它的速度。
在使用速度测试时,问题似乎主要在于嵌套的 for 循环。计算距离的循环似乎比较快。
作为对代码的解释,我正在使用 openCV 读取图像,浏览该图像,并找到离给定位置最近的像素。我想在嵌套的 for 循环中忽略条件中的某些颜色,以及忽略代码中其他地方以前访问过的像素。
found = False
randArray = []
for i in range(0,imgCol):
for j in range(0,imgRow):
if(pixelInLine[j*imgCol + i] == 0 and numpy.any(img2[j, i] != 0) and isWhite(j,i) == False):
found = True
temp = points(j,i)
pointArray.append(temp)
#The pixelsInLine is to ignore previously visited pixels
#The rest of the above conditional is to ignore colors I don't want
myDist = 0
currDist = sys.maxsize
distArray = []
for sx in pointArray:
myDist = math.sqrt( ((currR-sx.rr)**2)+((currC-sx.cc)**2))
if myDist == currDist:
distArray.append(sx)
if myDist < currDist:
distArray = []
distArray.append(sx)
currDist = myDist
if found == True:
rrr = distArray[0].rr
ccc = distArray[0].cc
【问题讨论】:
-
你可能想在遇到 if 条件后打破循环,找到 = True ?
-
我过去做过,是的,速度要快得多。这是个好主意,我很欣赏它,但它只是在循环中找到第一个可用像素。这不是我真正想要的功能。我想找到最近的像素,一个接近的像素,或者至少是一种比从左到右从上到下找到第一个开放点更有机的算法。
-
应该可以迁移到 CodeReview 站点,但我无法标记该站点。
标签: python python-3.x performance optimization