- API:normalize
- 图像运算时转为float32以保持精度,显示时转为uint8类型。
在 NORM_MINMAX 模式下,alpha表示归一化后的最小值,beta表示归一化后的最大值。
在NORM_L1、NORM_L2、NORM_INF 模式下,alpha表示执行相应归一化后矩阵的范数值,beta不使用。
C++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char *argv[])
{
Mat src = imread("D:/vcprojects/images/test.png");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
Mat gray, gray_f;
cvtColor(src, gray, COLOR_BGR2GRAY);
// 转换为浮点数类型数组
gray.convertTo(gray, CV_32F); // 从CV_8UC1转为CV_32F
// scale and shift by NORM_MINMAX
Mat dst = Mat::zeros(gray.size(), CV_32FC1);
normalize(gray, dst, 1.0, 0, NORM_MINMAX);
Mat result = dst * 255;
result.convertTo(dst, CV_8UC1);
imshow("NORM_MINMAX", dst);
// scale and shift by NORM_INF
normalize(gray, dst, 1.0, 0, NORM_INF);
result = dst * 255;
result.convertTo(dst, CV_8UC1);
imshow("NORM_INF", dst);
// scale and shift by NORM_L1
normalize(gray, dst, 1.0, 0, NORM_L1);
result = dst * 10000000;
result.convertTo(dst, CV_8UC1);
imshow("NORM_L1", dst);
// scale and shift by NORM_L2
normalize(gray, dst, 1.0, 0, NORM_L2);
result = dst * 10000;
result.convertTo(dst, CV_8UC1);
imshow("NORM_L2", dst);
waitKey(0);
return 0;
}
Python
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) # 数据类型要采用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)) # 转为uint8格式
# 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()