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.

Derte Trdelnik
  • 2,656
  • 1
  • 22
  • 26
MaxouMask
  • 985
  • 1
  • 12
  • 33

1 Answers1

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

ractiv
  • 712
  • 8
  • 19
  • 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. – MaxouMask Jan 07 '19 at 16:48
  • Good news! I wrote and tested quickly, I did not notice the inversion of the two arrays, sorry. – ractiv Jan 07 '19 at 16:51