什么是归一化
归一化是指在处理数据的过程中,把数据范围相差较大的数据进行标准化处理,让所有的数据都处于同一个数量级中,在opencv中具体实现有4种方式
步骤1:在pycharm中查看帮助
输入指令 import cv2 as cv
help(cv.normalize)
步骤2:在这里可以看到有4种的归一化方式
方式1:NORM_L1
. // Norm to probability (total count)
. // sum(numbers) = 20.0
. // 2.0 0.1 (2.0/20.0)
. // 8.0 0.4 (8.0/20.0)
. // 10.0 0.5 (10.0/20.0)
. normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1);
方式2:NORM_L2
公式:
// Norm to unit vector: ||positiveData|| = 1.0
. // 2.0 0.15 0.15=2/sqrt(2*2+8*8+10*10)
. // 8.0 0.62 0.62=8/sqrt(2*2+8*8+10*10)
. // 10.0 0.77 0.77=10/sqrt(2*2+8*8+10*10)
. normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2);
方式3:NORM_INF
公式:
// Norm to max element
. // 2.0 0.2 (2.0/10.0)
. // 8.0 0.8 (8.0/10.0)
. // 10.0 1.0 (10.0/10.0)
. normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF);
方式4:NORM_MINMAX
公式
// Norm to range [0.0;1.0]
. // 2.0 0.0 (shift to left border)
. // 8.0 0.75 (6.0/8.0)
. // 10.0 1.0 (shift to right border)
. normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX);
步骤3:在python中实现四种方式
main.py代码
from numpy import *
from cv2 import *
import OpencvFunc as fc
from matplotlib import pyplot as plt
if __name__ == '__main__':
titles = ['Orginal', 'NORM_MINMAX','NORM_L1','NORM_L2','NORM_INF']
Orginalimg=fc.OpenImage("F:/OpencvTest/fail.jpg")
#NORM_MINMAX
NORM_MINMAXimg = zeros(Orginalimg.shape, float32)
NORM_MINMAXimg=fc.normalize(Orginalimg,NORM_MINMAXimg,NORM_MINMAX)
print(NORM_MINMAXimg)
# NORM_L1
NORM_L1img = zeros(Orginalimg.shape, float32)
NORM_L1img=fc.normalize(Orginalimg,NORM_L1img,NORM_L1)
print(NORM_L1img)
# NORM_L2
NORM_L2img = zeros(Orginalimg.shape, float32)
NORM_L2img=fc.normalize(Orginalimg,NORM_L2img,NORM_L2)
print(NORM_L2img)
# NORM_INF
NORM_INFimg = zeros(Orginalimg.shape, float32)
NORM_INFimg=fc.normalize(Orginalimg,NORM_INFimg,NORM_INF)
print(NORM_L2img)
images = [Orginalimg, NORM_MINMAXimg, NORM_L1img, NORM_L2img, NORM_INFimg]
for i in range(len(images)):
plt.subplot(3, 3, i + 1)
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
k=waitKey(0)
OpencvFunc.py代码
from numpy import *
import cv2 as cv
def OpenImage(file):
im = cv.imread(file) # 在工程目录下放一张图片
if im is None:
print("image as null")
im = cv.cvtColor(im, cv.COLOR_RGB2GRAY)
return im
def normalize(src,dst,NormalType):
if NormalType=="NORM_L1":
NormalType = "NORM_L1"
elif NormalType=="NORM_L2":
NormalType = "NORM_L2"
elif NormalType == "NORM_INF":
NormalType = "NORM_INF"
elif NormalType == "NORM_MINMAX":
NormalType = "NORM_MINMAX"
src = float32(src)
# print(src)
# NORM_MINMAX
dst = zeros(src.shape, float32)
#print(dst)
cv.normalize(src,dst,1.0,0.0,NormalType)
return dst
图形效果显示