import cv2
import numpy as np
cv2.namedWindow('levels', cv2.WINDOW_NORMAL)
width = 400
height = 300
image = np.ones((height, width), dtype=np.uint8)
for num in range(width):
image[:, num] = 0 + num / (width - 1) * 255
def linear(pos, wpilv, bpilv, wpolv, bpolv):
return int(bpolv + (pos - bpilv) * (wpolv - bpolv) / (wpilv - bpilv))
def process(value):
width = 400
height = 300
for num in range(width):
image[:, num] = 0 + num / (width - 1) * 255
wpilv = cv2.getTrackbarPos('White Point Input Level', 'levels')
bpilv = cv2.getTrackbarPos('Black Point Input Level', 'levels')
wpolv = cv2.getTrackbarPos('White Point Output Level', 'levels')
bpolv = cv2.getTrackbarPos('Black Point Output Level', 'levels')
height, width = image.shape[0:2]
for y in range(height):
for x in range(width):
v = image[y, x]
#print("v=======",v)
if v <= bpilv:
image[y, x] = bpolv
elif v >= wpilv:
image[y, x] = wpolv
else:
image[y, x] = linear(v, wpilv, bpilv, wpolv, bpolv)
cv2.imshow('levels', image)
def midtone_control(value):
for num in range(width):
image[:, num] = 0 + num / (width - 1) * 255
Hin = cv2.getTrackbarPos('White Point Input Level', 'levels')
Sin = cv2.getTrackbarPos('Black Point Input Level', 'levels')
Hout = cv2.getTrackbarPos('White Point Output Level', 'levels')
Sout = cv2.getTrackbarPos('Black Point Output Level', 'levels')
Mid = cv2.getTrackbarPos("Midtone Control","levels")
Mt = (Mid - Sin) / (Hin - Mid)
Sin = min(max(Sin, 0), Hin-2) # Sin, 黑场阈值, 0<=Sin<Hin
Hin = min(Hin, 255) # Hin, 白场阈值, Sin<Hin<=255
Mt = min(max(Mt, 0.01), 9.99) # Mt, 灰场调节值, 0.01~9.99
Sout = min(max(Sout, 0), Hout-2) # Sout, 输出黑场阈值, 0<=Sout<Hout
Hout = min(Hout, 255) # Hout, 输出白场阈值, Sout<Hout<=255
difIn = Hin - Sin
difOut = Hout - Sout
table = np.zeros(256, np.uint16)
for i in range(256):
V1 = min(max(255 * (i-Sin)/difIn,0), 255) # 输入动态线性拉伸
V2 = 255 * np.power(V1/255, 1/Mt) # 灰场伽马调节
table[i] = min(max(Sout+difOut*V2/255, 0), 255) # 输出线性拉伸
new_image = cv2.LUT(image, table)
print(table,new_image)
cv2.imshow('new_levels', new_image)
cv2.createTrackbar('Black Point Input Level', 'levels', 0, 255, process)
cv2.createTrackbar('White Point Input Level', 'levels', 0, 255, process)
cv2.createTrackbar('Black Point Output Level', 'levels', 0, 255,process)
cv2.createTrackbar('White Point Output Level', 'levels', 0, 255,process)
cv2.createTrackbar('Midtone Control', 'levels', 0, 255, midtone_control)
cv2.setTrackbarPos('Black Point Input Level', 'levels', 0)
cv2.setTrackbarPos('White Point Input Level', 'levels', 255)
cv2.setTrackbarPos('Black Point Output Level', 'levels', 0)
cv2.setTrackbarPos('White Point Output Level', 'levels', 255)
cv2.setTrackbarPos('Midtone Control', 'levels', 128)
cv2.imshow('levels', image)
cv2.waitKey()
cv2.destroyAllWindows()
- 经过LUT之后的图像理论上来说应该也是一个渐变,但是实际上却不是
- 问题怎么解决呢?