2 different outputs with similar loops

I couldn’t understand the reason I get two different outputs with the following codes.
The first one gives the correct output.

While images are fine to illustrate points, please provide copy/pastable code examples by placing code between 3 backticks. You will find more people willing to help if they do not have to transcribe all of your code from an image to test your code in order to help.

my code here

With all of that said, in the first example, it seems for every pixel you are resetting mean to zero, but in the second example, you set mean to zero at the very start of processing the image, but never again.

In short, the second loop has a “dirty” mean. It is already populated with the last pixel’s mean, while the first loop starts each pixel calculation with a “clean” slate (zero). That is just the first thing I noticed.

Secondly, the way you are setting the arrays in each loop is very different. x_gray[i, j]=mean looks to set a single pixel to use the mean for all of the color channels while x_gray[:,:,:]=mean sets the entire matrix of pixels to the mean every time it processes a new pixel.

I have not tried out your code, but I would argue the second loop is not what you want at all. There could be more issues as I could not copy/paste your code and try it out. I also don’t have access to the image you are processing.

Thank you so much, I got it. I’m a beginner in python and this is my first post here. I will follow your recommendation in my next posts.