11 像素归一化
代码
import cv2 as cv
import numpy as np
src = cv.imread("../image/coins.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
# 转换为浮点数类型数组
gray = np.float32(gray)
print(gray)
# scale and shift by NORM_MINMAX
dst = np.zeros(gray.shape, dtype=np.float32)
cv.normalize(gray, dst=dst, alpha=0, beta=1.0, norm_type=cv.NORM_MINMAX)
print(dst)
cv.imshow("NORM_MINMAX", np.uint8(dst*255))
# scale and shift by NORM_INF
dst = np.zeros(gray.shape, dtype=np.float32)
cv.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv.NORM_INF)
print(dst)
cv.imshow("NORM_INF", np.uint8(dst*255))
# scale and shift by NORM_L1
dst = np.zeros(gray.shape, dtype=np.float32)
cv.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv.NORM_L1)
print(dst)
cv.imshow("NORM_L1", np.uint8(dst*10000000))
# scale and shift by NORM_L2
dst = np.zeros(gray.shape, dtype=np.float32)
cv.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv.NORM_L2)
print(dst)
cv.imshow("NORM_L2", np.uint8(dst*10000))
cv.waitKey(0)
cv.destroyAllWindows()
实验结果
解释
opencv中提供了四种归一化的方法:
- NORM_MINMAX
- NORM_INF
- NORM_L1
- NORM_L2
最常用的就是NORM_MINMAX归一化方法
L1 归一化(依据是:和为1)
2.0+8.0+10.0=20
2.0 0.1 (2.0/20.0)
8.0 0.4 (8.0/20.0)
10.0 0.5 (10.0/20.0)
L2 归一化(依据是:单位向量为1,也即每个数除以 根号下所有数的平方和)
2.0 0.15
8.0 0.62
10.0 0.77
NORM_INF 归一化(依据是:最大值)
2.0 0.2 (2.0/10.0)
8.0 0.8 (8.0/10.0)
10.0 1.0 (10.0/10.0)
NORM_MINMAX 归一化(依据是:delta=max-min,也即最小值为0,最大值为1)
2.0 0.0 (0.0/8.0)
8.0 0.75 (6.0/8.0)
10.0 1.0 (8.0/8.0)
注意:在计算过程中将数值转换为float或者double型,防止计算过程中精度的损失。
注意:归一化后在imshow
图片时,需要*255
所有内容均来源于贾志刚老师的知识星球——OpenCV研习社,本文为个人整理学习,已获得贾老师授权,有兴趣、有能力的可以加入贾老师的知识星球进行深入学习。