Ser*_* S. 5 python arrays opencv numpy image-processing
我正在尝试增加灰度图像的亮度.cv2.imread()返回一个numpy数组.我正在为数组的每个元素添加整数值.从理论上讲,这会增加每一个.之后,我可以将上限阈值设为255,并获得更高亮度的图像.
这是代码:
grey = cv2.imread(path+file,0)
print type(grey)
print grey[0]
new = grey + value
print new[0]
res = np.hstack((grey, new))
cv2.imshow('image', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)
但是,内部OpenCV例程显然是这样的:
new_array = old_array % 255
Run Code Online (Sandbox Code Playgroud)
高于255的每个像素强度值变为除以255的余数.
结果,我变得黑暗而不是完全变白.
这是输出:
<type 'numpy.ndarray'>
[115 114 121 ..., 170 169 167]
[215 214 221 ..., 14 13 11]
Run Code Online (Sandbox Code Playgroud)
这是图像:
如何关闭此余数机制?有没有更好的方法来提高OpenCV的亮度?
Div*_*kar 14
一个想法是在添加value是否会通过检查255当前像素值之间的差异并检查它是否在内部之前检查添加是否会导致溢出value.如果确实如此,我们不会添加value,我们会直接设置255,否则我们会添加.现在,这个决策可以通过创建面具来缓解,并且 -
mask = (255 - grey) < value
Run Code Online (Sandbox Code Playgroud)
然后,进料该掩模/布尔阵列np.where让之间它选择255 和grey+value基于掩模.
因此,最后我们将实施 -
grey_new = np.where((255 - grey) < value,255,grey+value)
Run Code Online (Sandbox Code Playgroud)
样品运行
让我们用一个小代表性的例子来演示这些步骤.
In [340]: grey
Out[340]:
array([[125, 212, 104, 180, 244],
[105, 26, 132, 145, 157],
[126, 230, 225, 204, 91],
[226, 181, 43, 122, 125]], dtype=uint8)
In [341]: value = 100
In [342]: grey + 100 # Bad results (e.g. look at (0,1))
Out[342]:
array([[225, 56, 204, 24, 88],
[205, 126, 232, 245, 1],
[226, 74, 69, 48, 191],
[ 70, 25, 143, 222, 225]], dtype=uint8)
In [343]: np.where((255 - grey) < 100,255,grey+value) # Expected results
Out[343]:
array([[225, 255, 204, 255, 255],
[205, 126, 232, 245, 255],
[226, 255, 255, 255, 191],
[255, 255, 143, 222, 225]], dtype=uint8)
Run Code Online (Sandbox Code Playgroud)
测试样本图像
使用问题中发布的样本图片给我们arr并使用valueas 50,我们将 -
这是另一种选择:
# convert data type
gray = gray.astype('float32')
# shift pixel intensity by a constant
intensity_shift = 50
gray += intensity_shift
# another option is to use a factor value > 1:
# gray *= factor_intensity
# clip pixel intensity to be in range [0, 255]
gray = np.clip(gray, 0, 255)
# change type back to 'uint8'
gray = gray.astype('uint8)
Run Code Online (Sandbox Code Playgroud)