Ofek Ron
Ofek Ron

Reputation: 8580

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?

Upvotes: 1

Views: 75

Answers (2)

kai06046
kai06046

Reputation: 292

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

Upvotes: -1

DYZ
DYZ

Reputation: 57033

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.

Upvotes: 3

Related Questions