简体   繁体   中英

Optimizing this python code

Im running this to fill image bottom starting from some upper pixel with value>0:

def fillDown(im):
    h,w=im.shape
    for i in range(w):
        for j in range(h):
            if im[j][i]>0:
                for k in range(j,h):
                    im[k][i]=255
                break

This takes far too long on large images, how would you suggest to optimize this?

I believe the following code does what you are looking for:

im = np.array([[0,0,0,0],[0,0,1,1],[0,0,0,1],[0,1,1,1]]) # Example
#array([[0, 0, 0, 0],
#       [0, 0, 1, 1],
#       [0, 0, 0, 1],
#       [0, 1, 1, 1]])

im[im.cumsum(axis=0) > 0] = 255
#array([[  0,   0,   0,   0],
#       [  0,   0, 255, 255],
#       [  0,   0, 255, 255],
#       [  0, 255, 255, 255]])

Hopefully it is more efficient than the triple nested loop.

I would like to use numpy to do this.

import numpy as np

im = np.random.ranint(0, 2, (2, 2))
im[np.where(im > 0)] = 255

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