1

i created an algorithm with two for-loops for my gray image. Every pixel above the value 180 and on the left side of the image gets a new value.

This algorithm is very slow and takes a few seconds.

Is there a faster way to do this job?

   for x in range(img.shape[0]):
        for y in range(img.shape[1]):
            if(img[x,y]>180 or y>450):
                img[x,y]=255
Dschoni
  • 3,714
  • 6
  • 45
  • 80
Edwin B.
  • 41
  • 5

1 Answers1

1

You should employ vectorized numpy operations, something like

img[img > 180] = 255
img[:,450:] = 255

Should do exactly what your loop does, but much more quickly. To apply both conditions together you can do

img[:,450:][img[:,450:] > 180] = 255
William Miller
  • 9,839
  • 3
  • 25
  • 46
  • I found a mistake in my code. It should be 'and' instead of 'or'. Is it possible to use these operators in an and-condition? – Edwin B. Apr 01 '20 at 08:13
  • @EdwinB. See the edit, and if this answers your question don't neglect to [accept](https://stackoverflow.com/help/someone-answers) it so the question is marked as such for future users. – William Miller Apr 01 '20 at 08:16
  • I don't know why, but the code is not working. Is there maybe a problem with the brackets? – Edwin B. Apr 01 '20 at 08:24
  • @EdwinB. My apologies, I have fixed it - should work now. – William Miller Apr 01 '20 at 08:26
  • Thanks, now its working, but somehow it changes only the pixels on the right side of the image. But the solution should be simple – Edwin B. Apr 01 '20 at 08:32
  • @EdwinB. If you want to apply to the left size instead simply change `img[:,450:]` to `img[:,:450]` – William Miller Apr 01 '20 at 08:33