问题描述
由于我已经在Matlab中完成了这些实验,因此我尝试在Matlab中完成一些我们打算在python中进行视频分析模块的实验,但是我在加亮图像方面遇到了问题。我已经将图像毫无问题地读入Numpy数组中,但是当我使用以下代码尝试将其变亮然后显示时:
def imageProcessing(self,imageLocation):
image = numpy.array(Image.open(imageLocation))
imageGreyScale = numpy.array(Image.open(imageLocation).convert('L'))
imageReadable = Image.fromarray(imageGreyScale)
imageReadable.show()
matplotlib.pyplot.hist(imageGreyScale.ravel(),256,[0,256]);
matplotlib.pyplot.show()
imageGreyScale = imageGreyScale+50
imageReadableBrighter = Image.fromarray(imageGreyScale)
imageReadableBrighter.show()
matplotlib.pyplot.hist(imageGreyScale.ravel(),256]);
matplotlib.pyplot.show()
由于某种原因,而不是将255(最大灰度)的50之内的数据剪切为255,像素值似乎达到255,然后又回到0,然后增加了多少(剩下的图表)。在处理之前,红色的位在绿色的位旁边,但是可以说,不是被剪切,而是被“环回”了) Graph of the histogram after adding 50 to every pixel value
现在,我尝试添加条件赋值语句,例如Numpy.where()等,但似乎无法使其正常工作。谁能解释发生了什么或如何解决?谢谢。
使用: Python版本3.5, 最新版本的Numpy, 最新版本的PIL, 在最新版本的MacOS上
解决方法
为什么250 + 50 = 44?
就位而言,以这种方式实现是最简单的。在8位加法中,将计算所有8位,并且不存储第9位(300 = 100101100b,44 = 101100b)。
如果以检查溢出然后将值替换为最小或最大有效值的方式实现CPU,则计算仍将是错误的,在某些情况下甚至会更糟,并且即使存在不会有溢出的机会。
如何使250 + 50 = 255?
CPU不会自动为您完成操作,但是您可以自己完成操作。
您要执行的操作是将y = x + 50
替换为:
if x < 205:
y = x + 50
else:
y = 255
要在大型numpy数组上有效地执行此操作,请执行以下操作:
x = np.array([1,2,3,100,200,220,250],dtype=np.uint8)
y = x + 50
y[x > 205] = 255 # or y[y < 50] = 255
或更短,根据您的情况:
imageGreyScale += 50
imageGreyScale[imageGreyScale < 50] = 255