简体   繁体   中英

Speeding Up and Optimizing Python Loop

I have been banging my head against the wall for the last couple days, trying to optimize my code to improve speed. This chunk of code right here however is still quite slow, and I am not quite sure how to improve its speed specifically.

The problem, when using speed tests, seems to be primarily the nested for loop. The loop that calculates distance seems to be relatively quick.

As an explanation of the code, I am reading in images using openCV, going through that image, and finding the nearest pixel to a given location. I want to ignore certain colors within my conditional in the nested for loop, as well as ignore previously visited pixels elsewhere in my code.

    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

It's difficult to tell exactly what's going on, but my understanding is that you're trying to find the set of pixels that satisfy some property and have the smallest Euclidean distance from some other pixel. If that's the case, rather than testing every single pixel in the array, why not start with the closest pixels? If/when you find ones that satisfy the desired properties, you can stop searching, because you know that there aren't any that are closer.

If you are doing this for many pixels, the part with the conditionals doesn't depend on the pixel you are looking at at the moment. An improvement would the be to do this O(n^2) pixel selection only once, and late on only update it when you update pixelInLine eg

As @mackorone noticed, you can also try to enumerate the pixels from the closest to the farthest. But then it depends if you are expecting pointArray to be big or small. If it's small enough, going through all of it can be quicker than a fancy enumeration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM