通过np.clip函数进行调整
numpy.clip(x, x_min, x_max, out=None)[source]
其中a是一个数组,后面两个参数分别表示最小和最大值,也就是说clip这个函数将将数组中的元素限制在x_min, x_max之间,大于x_max的就使得它等于 x_max,小于x_min,的就使得它等于x_min。
import numpy as np
x=np.array([1,2,3,4,5,6,7,8,9])
dst = np.clip(x,4,8)
print(dst)
可以看到,输出的纬度不变,根据上下限修改了数据。
创建两个滑动条分别调整对比度和亮度(对比度范围:0 ~ 0.3, 亮度0 ~ 100)。提示:因为滑动条没有小数,所以可以设置为0 ~ 300,然后乘以0.01
#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys
#对比度范围:0 ~ 0.3
alpha = 0.3
#亮度范围0 ~ 100
beta = 100
img = cv.imread('E:/chenopencvblogimg/test1.jpg')
img2 = cv.imread('E:/chenopencvblogimg/test1.jpg')
def updateAlpha(x):
global alpha, img, img2
alpha = cv.getTrackbarPos('Alpha', 'image')
alpha = alpha * 0.01
img = np.uint8(np.clip((alpha * img2 + beta), 0, 255))
def updateBeta(x):
global beta, img, img2
beta = cv.getTrackbarPos('Beta', 'image')
img = np.uint8(np.clip((alpha * img2 + beta), 0, 255))
def img_test():
global beta, img, img2
#判断是否读取成功
if img is None:
print("Could not read the image,may be path error")
return
# 创建窗口
cv.namedWindow('image',cv.WINDOW_NORMAL)
cv.createTrackbar('Alpha', 'image', 0, 300, updateAlpha)
cv.createTrackbar('Beta', 'image', 0, 255, updateBeta)
cv.setTrackbarPos('Alpha', 'image', 100)
cv.setTrackbarPos('Beta', 'image', 10)
while (True):
cv.imshow('image', img)
if cv.waitKey(1) == ord('q'):
break
cv.destroyAllWindows()
if __name__ == '__main__':
sys.exit(img_test() or 0)
用到了函数addweighted
cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]]) → dst
same size and channel
number as src1
.same size and number of channels
as the input arrays.dtype
can be set to -1
, which will be equivalent to src1.depth()
.此函数可以用一下矩阵表达式来代替:
dst = src1 * alpha + src2 * beta + gamma;
#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys
#对比度亮度调整
def img_contrast_bright(img,a,b,g):
h,w,c = img.shape
blank = np.zeros([h,w,c],img.dtype)
dst = cv.addWeighted(img,a,blank,b,g)
return dst
def img_test():
img = cv.imread('E:/chenopencvblogimg/mofan.jpg')
#判断是否读取成功
if img is None:
print("Could not read the image,may be path error")
return
cv.namedWindow("origin Pic",cv.WINDOW_NORMAL)
cv.imshow("origin Pic",img)
#调整亮度对比度
#img = img_contrast_bright(img,0.3,0.7,0)
a = 1.2
b = 1-a
g = 10
img = img_contrast_bright(img,a,b,g)
cv.namedWindow("img_adjusted",cv.WINDOW_NORMAL)
cv.imshow("img_adjusted",img)
#让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
cv.waitKey(0)
#销毁窗口
cv.destroyAllWindows()
if __name__ == '__main__':
sys.exit(img_test() or 0)