gpt4 book ai didi

python - 全局集中然后标准化图像

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:02 25 4
gpt4 key购买 nike

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

# 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)

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

Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).

然后使用plt.imsave函数

ValueError: Floating point image RGB values must be in the 0..1 range.

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

最佳答案

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

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)

关于python - 全局集中然后标准化图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60324296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com