全局集中,然后规格化图像



我正在尝试使用全局集中图像

# example of global centering (subtract mean)
from numpy import asarray
from PIL import Image
# load image
image = Image.open('13.jpg')
pixels = asarray(image)
# convert from integers to floats
pixels = pixels.astype('float32')
# calculate global mean
mean = pixels.mean()
print('Mean: %.3f' % mean)
print('Min: %.3f, Max: %.3f' % (pixels.min(), pixels.max()))
# global centering of pixels
global_pixels = pixels - mean
# confirm it had the desired effect
mean = global_pixels.mean()
print('Mean: %.3f' % mean)
print('Min: %.3f, Max: %.3f' % (global_pixels.min(), global_pixels.max()))

然后使用进行集中

# normalize to the range 0-1
pixels_new = global_pixels/ 255.0
# confirm the normalization
print('Min: %.3f, Max: %.3f' % (pixels_new.min(), pixels_new.max()))
plt.imshow(np.array(pixels_new))
plt.imsave('test1.png', pixels_new)

我收到警告,然后出现错误

使用RGB数据将输入数据剪裁到imshow的有效范围([0.1]表示浮点,[0.255]表示整数(。

然后在plt.imsave函数上

ValueError:浮点图像RGB值必须在0..1范围内。

有人能解释一下出了什么问题吗?

我更喜欢opencv,因为它的粉丝群更大,更容易与numpy结合使用。我给你写了一个如何处理红色通道的简短例子,因为我假设你想分别平均所有三层,并分别应用每个通道的平均值:

from numpy import asarray
import cv2
import numpy as np
import matplotlib.pyplot as plt
path="/content/111.jpg"
# load image
img=cv2.imread(path,1)
# mean Pixel of Red layer
mean_R=np.sum(img[:,:,0])/(img.shape[0]*img.shape[1])
# Subtract calculated Mean_Red from all pixels
img_red_new=img[:,:,0]-mean_R
#eliminate all negative values
img_red_new=(img_red_new>=0)*img_red_new

# Validate Images and values
plt.imshow(img_red_new)
plt.figure()
plt.imshow(img[:,:,0])
print("Red_New:",np.max(img_red_new))
print("Red_old:",np.max(img[:,:,0]))
print("Mean:",mean_R)
# Safe as Image
cv2.imwrite("test.jpg",img_red_new)

最后,你的错误是因为你必须定义一个值范围,在这个范围内你的颜色被表示。在0-1或0-255之间,这是你的选择,但你必须选择一个。因此,只需通过以下方式规范化您的图像:

max=np.max(image)
image=image/max --> values 0-1

此外,您可以通过以下方式将其转换回无符号整数(0-255(:

image=image*255
image=image.astype(np.uint8)

通过更改

plt.imshow(np.array(pixels_new))

plt.imshow(np.array(pixels* 255).astype(np.uint8))

这解决了的两个问题

似乎与此有关https://github.com/matplotlib/matplotlib/issues/9391/

Orginally from here

最新更新