本文介绍了在满足条件的同时,找到相对于另一个像素最近的像素的最快方法. OpenCV脾气暴躁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最快的读取图像的方式,指定一个像素,并在有条件的情况下找到与该像素最接近的像素.

I am looking for the fastest way that I can read an image in, specify a pixel, and find the nearest pixel to that pixel given my conditionals.

我最初有一个嵌套循环,该循环将遍历2D图像阵列中的每个像素,检查是否有条件,然后再将其添加到新阵列中.比遍历新数组对每个成员进行距离计算.我认为那太慢了,时间复杂度为n ^ 2.

I originally had a nested loop that would go through each pixel in my 2D image array, check for conditional, than add it to a new array. Than go through the new array and do the distance calculations on each member.That was terribly slow, and has a time complexity of n^2 I believe.

我现在正在进行距离计算,并以此对数组进行排序,这在使用numpy时非常快.但是然后我仍然必须通过带有嵌套循环的2D排序数组来检查条件,这又是n ^ 2的时间复杂度.但这确实节省了一些时间,因为我通常可以在阵列中更快地找到所需的像素.

I am now doing the distance calculations, and sorting the array by that, which is quite fast when using numpy. But then I still have to go through that 2D sorted array with a nested loop to check for conditionals, which again is a time complexity of n^2. It does save some time though because I can normally find the pixel I am looking for sooner in the array.

img2=cv2.imread(filename)
distances = numpy.sqrt((img2[:,:] - currR) ** 2 + (img2[:,:] - currC) ** 2)
nearest = numpy.sort(distances)
for row in range(nearest.shape[0]):
    for col in range(nearest.shape[1]):
        if pixelInLine[row*imgCol + col] == 0  and colorCheck(row,col) and numpy.any(img2[row, col] != 0):
            #do my calculations on the specified pixel. and break the loop

我不确定如何进一步优化它,并且可能将时间复杂度从n ^ 2降低到更合理的水平.

I am unsure how I can optimize this further, and potentially lower the time complexity from n^2 to something more reasonable.

推荐答案

一旦达到条件",就逐渐远离目标像素旋转并停止.为方便起见,您可以使用正方形螺旋(实际上是嵌套的正方形).

Go spiraling away from the target pixel and stop as soon as you meet the "conditionals". For convenience, you can use a square spiral (in fact nested squares).

如果距离是欧几里得,则搜索成本将在2d²和4d²之间,其中d是到匹配的距离.

If the distance is Euclidean, the cost of the search will be between 2d² and 4d² where d is the distance to the hit.

这篇关于在满足条件的同时,找到相对于另一个像素最近的像素的最快方法. OpenCV脾气暴躁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:17