假设我有一个400*300灰度的image.Now,我想要水平扫描每一行,并使该行128的平均值,从而使值按其与平均值(128)的差值进行缩放,这将不会对图像造成任何失真。
发布于 2015-12-24 14:41:00
下面是一个关于如何使用Python、Numpy和Matplotlib实现此操作的示例。右边的图像已被平均化(逐行),而左边是原始图像。

编辑:正如@Nathan建议的那样,当行平均值为0时,我避免了翻转颜色。平均为0的行现在得到的值为0.5 (128)。以前遇到的暗图像是由于缩放导致的值高于1 (255),在matplotlib的图像渲染器中表示为白色。我通过将任何像素中的最大值设置为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()下面是一个简单的梯度图像(左是原始图像)的另一个测试:

https://computergraphics.stackexchange.com/questions/1830
复制相似问题