Python openCV 使用零均值和单位方差进行归一化

标签 python opencv

我正在尝试使用 cv2.normalize 函数对具有零均值和单位方差的灰度图像数组进行归一化,如下所示

out_image = np.zeros((32,32),dtype=np.float32)
out_array = np.zeros((len(X),32,32), dtype=np.uint8)        
for imageindex in range(0,len(X)): 
    img = X[imageindex].squeeze()
    if proctype == 'MeanSubtraction':
        out_image = img.astype(np.float32) - np.mean(img.astype(np.float32))
    elif proctype == 'Normalization':
        out_image = cv2.normalize(img.astype(np.float32), out_image, alpha=-0.5, beta=0.5,\
                                             norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
    elif proctype == 'HistEqualization':
        out_image = cv2.equalizeHist(img)

    elif proctype == 'CLAHE':
        clahe = cv2.createCLAHE(tileGridSize=(6,6),clipLimit = 20.0)
        out_image = clahe.apply(img)

    out_array[imageindex] = out_image.astype(np.uint8)

return out_array

但是,如果我使用 0 和 1(或 0 和 255)作为标准化函数的参数 alpha 和 beta,它就可以工作。但如果我使用 -0.5 和 +0.5,它会返回一个空图像(全为零)

为什么会发生这种情况?

最佳答案

out_array的类型为np.uint8,因此无法准确表示浮点值。因此,当您使用 将包含 [-0.5, 0.5] 范围内的浮点值的 out_image 转换为 np.uint8 时>out_image.astype(np.uint8),所有这些值都被截断为零。考虑这个例子:

# generate random numbers in the range [-0.5, 0.5]
x_float32 = (np.random.random((32, 32)) - 0.5).astype(np.float32)
print x_float32.min(), x_float32.max()  # prints -0.49861032, 0.4998906
x_uint8 = x_float32.astype(np.uint8)
print x_uint8.min(), x_uint8.max()      # prints 0, 0

如果要在out_array中存储浮点值,首先需要将其dtype更改为np.float32。或者,您可以将 [-0.5, 0.5] 范围内的值重新规范化为 [0, 255] 范围内的无符号整数。

关于Python openCV 使用零均值和单位方差进行归一化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42346194/

相关文章:

python - Gunicorn 不选择 stderr

python - 匹配 Python 整数文字的正则表达式

python - 如何调试异步python代码?

c++ - vector 的 OpenCV vector 转换为 cv::Mat

java - 如何使用 OpenCV 的 Watershed Transform 实现过分割?

python - aiohttp.TCPConnector (with limit argument) vs asyncio.Semaphore 用于限制并发连接数

python - test_on_batch 和 train_on_batch 的不同损失值

opencv - 如何在 OpenCV 2.4.3 中保存(cvWrite 或 imwrite)图像?

python - 调整图片大小,仅在中心周围显示100x100像素

opencv - 使用 OpenCV 从小图像中提取点描述符