1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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

2 Comments

Your solution leaves unfilled "holes".
Look at the code in the question carefully. This doesn't do the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.