Looping over pixels in an image
I think the trick is trying to vectorise this as much as possible:

By the look of it, the code is trying to threshold at 0 and count pixels under 255.

We can change the first part of the loop to:

counter = np.sum(image_in &lt; 255) # Sums work on binary values
counter2 = np.sum(np.bitwise_and(image_in &lt; 255, image_in2 != 0)) 


And the second to:

# This is 0 or 1 depending on whether it is == 0
image_new[:,:] = (image_in2 != 0) # image_new[i,j] = (image_in2[i,j] != 0)

# So scale the values up with a simple multiplcation
image_new = image_new*255 # image_new[i,j] = image_new[i,j]*255