1

I'm looking for an efficient way to replace certain values within a numpy image. So far this is where I got :

def observation(self, img):
    # 45 50 184
    background = np.array([45, 50, 184])
    # 80 0 132
    border = np.array([80, 0, 132])
    img = self.crop(img)
    for line_index, line in enumerate(img):
        for pixel_index, pixel in enumerate(line):
            if not np.array_equal(pixel, background) and not np.array_equal(pixel, border):
                img[line_index][pixel_index] = [254, 254, 254]

The idea is to replace all the colors that are not background or border to white. I'm quite new to this, so I'm fairly sure that there is a more efficient way to do this.

Thanks all.

1 Answer 1

2

numpy.where should do the job. You have to call it twice (one for the background and one for the border) or combine the 2 conditions img != background and img != border:

np.where(np.logical_and(img!=background, img != border), img, [254, 254, 254])

See this post for a small example (possible duplicate?)

Hope it helps

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

2 Comments

It does the job, I had to change the order between img and the white color array, but it is indeed more efficient performance wise.
Good news! I wrote and tested quickly, I did not notice the inversion of the two arrays, sorry.

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.