opencv-011-图像像素归一化

知识点

OpenCV中提供了四种归一化的方法

  • NORM_MINMAX
  • NORM_INF
  • NORM_L1
  • NORM_L2

最常用的就是NORM_MINMAX归一化方法.

四种归一化方法示例

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 图像像素归一化
*/
int main() {
Mat src = imread("../images/test.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}
// imshow("input", src);

Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);
imshow("input", gray);

// 显示图像用uchar类型,计算时转为float类型
gray.convertTo(gray, CV_32F);

// NORM_MINMAX
Mat dst = Mat::zeros(gray.size(), CV_32FC1);
normalize(gray, dst, 1.0, 0, NORM_MINMAX);
Mat res = dst * 255;
res.convertTo(dst, CV_8UC1); // 显示图像用uchar类型
imshow("NORM_MINMAX", dst);

// scale and shift by NORM_INF
normalize(gray, dst, 1.0, 0, NORM_INF);
res = dst * 255;
res.convertTo(dst, CV_8UC1);
imshow("NORM_INF", dst);

// scale and shift by NORM_L1
normalize(gray, dst, 1.0, 0, NORM_L1);
res = dst * 10000000;
res.convertTo(dst, CV_8UC1);
imshow("NORM_L1", dst);

// scale and shift by NORM_L2
normalize(gray, dst, 1.0, 0, NORM_L2);
res = dst * 10000;
res.convertTo(dst, CV_8UC1);
imshow("NORM_L2", dst);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import cv2 as cv
import numpy as np

src = cv.imread("D:/vcprojects/images/test.png")
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()

结果

代码地址

github