调整对比和亮度
这篇教学会介绍使用 OpenCV 搭配 NumPy,调整图像的对比度和亮度,除此之外,也会使用 convertScaleAbs() 进行加强图像的效果。
快速导览:
因为程序中的 OpenCV 会需要使用镜头或 GPU,所以请使用本机环境 ( 参考:使用 Python 虚拟环境 ) 或使用 Anaconda Jupyter 进行实作 ( 参考:使用 Anaconda ) ,并安装 OpenCV 函数库 ( 参考:OpenCV 函数库 )。
搭配 NumPy 调整对比度和亮度
在 OpenCV 里读取的图像,实质上是 NumPy 的数组,因此在读取图像后,透过 NumPy“数组广播”的功能,就能迅速更改图片中每个像素的颜色,下方的例子,使用了简单的转换公式,只要调整 contrast ( 对比 ) 和 brightness ( 亮度 ) 的数值,就能改变图像的对比度和亮度。
import cv2
import numpy as np
img = cv2.imread('mona.jpg')
contrast = 200
brightness = 0
output = img * (contrast/127 + 1) - contrast + brightness # 轉換公式
# 轉換公式參考 https://stackoverflow.com/questions/50474302/how-do-i-adjust-brightness-contrast-and-vibrance-with-opencv-python
# 調整後的數值大多為浮點數,且可能會小於 0 或大於 255
# 為了保持像素色彩區間為 0~255 的整數,所以再使用 np.clip() 和 np.uint8() 進行轉換
output = np.clip(output, 0, 255)
output = np.uint8(output)
cv2.imshow('oxxostudio1', img) # 原始圖片
cv2.imshow('oxxostudio2', output) # 調整亮度對比的圖片
cv2.waitKey(0) # 按下任意鍵停止
cv2.destroyAllWindows()
下图为五张不同亮度和对比所产生的图片效果。
使用 convertScaleAbs() 加强图像
使用 OpenCV 的 convertScaleAbs 方法,可以根据特定的公式,转换图像中每个像素,使用方法如下:
cv2.convertScaleAbs(img, output, alpha, beta)
# img 來源影像
# output 輸出影像,公式:output = img*alpha + beta
# alpha, beta 公式中的參數
下方的程序码执行后,就会套用特定的参数进行加强图像的效果。
import cv2
import numpy as np
img = cv2.imread('mona.jpg')
output = img # 建立 output 變數
alpha = 1
beta = 10
cv2.convertScaleAbs(img, output, alpha, beta) # 套用 convertScaleAbs
cv2.imshow('oxxostudio', output)
cv2.waitKey(0) # 按下任意鍵停止
cv2.destroyAllWindows()
微信扫码关注
抖音扫码关注