Average intensity of an gray image
Here's an example on how to do this with Python, Numpy and Matplotlib.
Image on the right has been averaged (row by row), while the left is the original.



EDITED: As suggested by @Nathan Reed, I avoided flipping colors when row average is 0. Rows with an average of 0 now get a value of 0.5 (128). The dark image encountered previously was due to values higher than 1 (255) due to scaling, that were represented as white in matplotlib's image renderer. I fixed this by setting the max value in any pixel to be 1.

import numpy as np
from matplotlib import image as mpimg
from matplotlib import pyplot as plt

def rgb2gray(rgb):
    return np.dot( rgb[...,:3], [0.299, 0.587, 0.144] )

imgPath = "C:/myImg.jpg"

im = mpimg.imread( imgPath )
gs = rgb2gray( im )

averaged = gs.copy()

for row in averaged:
    rowAvg = sum( row ) / len( row )
    if rowAvg == 0:
        row = 0.5
    else:
        # Scale each row by ratio between 128 and current row avg
        row *= 0.5 / rowAvg

    # Make sure that no pixel has a higher value than 1
    if rowAvg &gt; 0: row[row&gt;1] = 1

plt.subplot( 1, 2, 1 ), plt.imshow( gs,       'gray' )
plt.subplot( 1, 2, 2 ), plt.imshow( averaged, 'gray' )

plt.show()


Here's another test with a simple gradient image (left is the original):