Pixel normalization in OpenCV

Normalization is to limit the data to a certain range after processing. The purpose of normalization is to make incomparable data comparable while maintaining the relative relationship between them.

The normalize method is used in opencv to achieve normalization, and its function prototype is as follows

 cv2.normalize(src, dst, alpha=None, beta=None, norm_type=None, dtype=None, mask=None)

in:

  • src: input matrix
  • dst: output matrix, same shape as input matrix
  • alpha: If norm_type is NORM_MINMAX , alpha is a large value or a small value; if norm_type is other types, it is the coefficient to be multiplied for normalization
  • beta: If norm_type is NORM_MINMAX , beta is a small value or a large value, corresponding to alpha ; if norm_type is other types, beta is ignored, generally pass in 0
  • norm_type: normalization type, common ones are NORM_MINMAX , NORM_INF , NORM_L1 , NORM_L2
  • dtype: The default type is the same as src , optional parameter
  • mask: optional operation mask, default is empty

Example

 import cv2 import numpy as np image = cv2.imread('lenna.png') cv2.imshow("original image", image) # 灰度图gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 转换为浮点数类型数组gray = np.float32(gray) # NORM_MINMAX,最常用的一种方法,数组的数值会被缩放到一个指定的范围,比如本例中的0~1 dst = np.zeros(gray.shape, dtype=np.float32) # 这里alpha=1, beta=0也是ok的cv2.normalize(gray, dst=dst, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) # 显示原图时,需要将像素值re-scale 到0~255 cv2.imshow("NORM_MINMAX", np.uint8(dst*255)) # NORM_INF,无穷范数,每个值除以最大值来进行无穷范数归一化dst = np.zeros(gray.shape, dtype=np.float32) cv2.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv2.NORM_INF) # 归一化后最大值就是1,所以也是*255 cv2.imshow("NORM_INF", np.uint8(dst*255)) # NORM_L1,1范数,每个值除以它们的和来进行归一化dst = np.zeros(gray.shape, dtype=np.float32) cv2.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv2.NORM_L1) # 归一化后范围是0~1,但最大值不是1,所以这里乘以一个足够大的数,你也可以取其它值,不一定是下面这个数。注意到np.uint8 的最大值是255,因此re-scale 的范围也是0~255 cv2.imshow("NORM_L1", np.uint8(dst*20000000)) # NORM_L2,2范数,每个值除以该向量的模长,归一化位单位向量dst = np.zeros(gray.shape, dtype=np.float32) cv2.normalize(gray, dst=dst, alpha=1.0, beta=0, norm_type=cv2.NORM_L2) # 与NORM_L1类似cv2.imshow("NORM_L2", np.uint8(dst*30000)) cv2.waitKey(0) cv2.destroyAllWindows()

This article is reprinted from https://xugaoxiang.com/2022/07/16/opencv-normalize/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment