这里有三种可能的方法来做到这一点。
第一个简单地将图像乘以因子 1.2 和阈值乘以因子 1.2 并使用新的阈值。
第二个将图像乘以因子 1.2,从阈值创建一个蒙版。使用蒙版使图像在所需区域变为黑白。
第三种方法更像您想要的,而无需处理整个图像。
输入(线性渐变图像):
import cv2
import numpy as np
# read image as grayscale
img = cv2.imread('grad.png', cv2.COLOR_BGR2GRAY)
# Method 1
# set threshold values
tlow = 50
thigh = 150
# multiply image by 1.2
result1 = img.copy()
result1 = (1.2 * result1).clip(0,255).astype(np.uint8)
# compute modified threshold values
tlow = int(1.2 * tlow)
thigh = int(1.2 * thigh)
result1[result1 <= tlow] = 0
result1[result1 > thigh ] = 255
print(tlow, thigh)
# Method 2
# set threshold values
tlow = 50
thigh = 150
# create mask that is black outside the desired range and white inside the desired range
mask = img.copy()
mask[mask <= tlow] = 0
mask[mask > thigh ] = 255
# modify input by 1.2 factor
result2 = img.copy()
result2 = (1.2 * result2).clip(0,255).astype(np.uint8)
# use mask to combine the input and the modified image
result2[mask==0] = 0
result2[mask==255] = 255
# method 3
# set threshold values
tlow = 50
thigh = 150
result3 = img.copy()
result3[result3 <= tlow] = 0
result3[result3 > thigh ] = 255
result3 = result3.astype(np.float32)
result3[(result3>50) & (result3<=150)] *= 1.2
result3 = result3.clip(0,255).astype(np.uint8)
# save result
cv2.imwrite("grad_process1.png", result1)
cv2.imwrite("grad_mask.png", mask)
cv2.imwrite("grad_process2.png", result2)
cv2.imwrite("grad_process3.png", result3)
# view result
cv2.imshow("result1", result1)
cv2.imshow("mask", mask)
cv2.imshow("result2", result2)
cv2.imshow("result3", result3)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果1:
结果 2:
结果 3: