1

我需要遍历二值化图像中的所有像素以找到形状。但是以这种方式迭代每个图像像素需要很长时间。有没有其他方法可以更快地迭代图像像素?

dimension = im.shape
rows = dimension[0]
cols = dimension[1]
for i in range(0,rows):
    for j in range(0,cols):
        doSomeOperation(im[i,j])
4

2 回答 2

1

一般来说,你doSomeOperation所做的决定了它可以加速多少。

如果提到的查找形状的兴趣实际上意味着查找连接的组件,那么加速解决方案的一种简单方法是使用包中的ndimage.labelndimage.find_objectsscipy

于 2012-12-08T13:53:55.367 回答
1

正如 rubik 的评论所说,与矢量化函数可以工作的速度相比,python 循环很慢。使用矢量化函数,您可以定义一个适用于单个元素的函数(如果您使用更复杂的矢量化函数,有时会更多)并返回单个值。常见的向量化函数已经定义为加法和乘法。

例如。

arr = numpy.arange(10)
arr = arr * numpy.arange(10, 20) 
# times all elements arr by the respective element in other array 
arr = arr + 1 
# add 1 to all elements

@numpy.vectorize
def threshold(element):
    if element < 20:
        return 0
    else:
        return element

# @ notation is the same as 
# threshold = numpy.vectorize(threshold)

arr = threshold(arr)
# sets all elements less than 20 to 0

但是,由于您正在尝试查找形状,因此可能值得说明您正在查看的像素区域。所以可能有更好的方法来尝试找到你正在寻找的东西。

于 2012-12-08T14:09:37.760 回答