可以使用 OpenCV 的 cv2.convertScaleAbs() 函數來增亮圖像。這個函數會將圖像的每個像素值乘上一個指定的比例因子並加上一個常數,以此來調整圖像的亮度。
請注意,這個函數可能會導致圖像中的一些像素值超出 0 到 255 的範圍,因此你可能需要在函數末尾使用new_image = np.where(new_image > 255, 255, new_image)來將這些像素值限制在合法範圍內。
import cv2
import numpy as np
# 讀取第一幅圖像
image = cv2.imread('image1.jpg')
def increase_brightness(image, value):
# 將圖像的每個像素值乘上指定的比例因子並加上常數
new_image = cv2.convertScaleAbs(image, alpha=1, beta=value)
# 將像素值限制在 0 到 255 之間
new_image = np.where(new_image > 255, 255, new_image)
return new_image
# 示例: 將圖像的亮度提高 50
bright_image = increase_brightness(image, 50)
# 示例: 將圖像的亮度降低50
dark_image = increase_brightness(image, -50)
# 顯示結果
cv2.imshow('image', image)
cv2.imshow('bright_image', bright_image)
cv2.imshow('dark_image', dark_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
