2026-02-10 11:17:31 +08:00
|
|
|
import cv2
|
2026-02-27 15:26:07 +08:00
|
|
|
import numpy as np
|
2026-02-10 11:17:31 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def my_imnormalize(img, mean, std, to_rgb=True):
|
|
|
|
|
"""Inplace normalize an image with mean and std.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
img (ndarray): Image to be normalized.
|
|
|
|
|
mean (ndarray): The mean to be used for normalize.
|
|
|
|
|
std (ndarray): The std to be used for normalize.
|
|
|
|
|
to_rgb (bool): Whether to convert to rgb.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
ndarray: The normalized image.
|
|
|
|
|
"""
|
|
|
|
|
# cv2 inplace normalization does not accept uint8
|
|
|
|
|
img = img.copy().astype(np.float32)
|
|
|
|
|
|
|
|
|
|
assert img.dtype != np.uint8
|
|
|
|
|
mean = np.float64(mean.reshape(1, -1))
|
|
|
|
|
stdinv = 1 / np.float64(std.reshape(1, -1))
|
|
|
|
|
if to_rgb:
|
|
|
|
|
cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) # inplace
|
|
|
|
|
cv2.subtract(img, mean, img) # inplace
|
|
|
|
|
cv2.multiply(img, stdinv, img) # inplace
|
|
|
|
|
return img
|