Suppose i have a 400*300 gray scale image.Now I want to scan each line horizontally and make the average of that line 128,such that the values get scaled as per their difference from mean(128) which will not cause any distortion to 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 > 0: row[row>1] = 1 plt.subplot( 1, 2, 1 ), plt.imshow( gs, 'gray' ) plt.subplot( 1, 2, 2 ), plt.imshow( averaged, 'gray' ) plt.show()