计算图像数据集RGB各通道的均值和方差

第一种写法,先读进来,再计算。比较耗内存。

import cv2
import numpy as np
import torch 

startt = 700
CNum = 100   # 挑选多少图片进行计算
imgs=[]
for i in range(startt, startt+CNum):
    img_path = os.path.join(root_path, filename[i])
    img = cv2.imread(img_path)
    img = img[:, :, :, np.newaxis]
    imgs.append(torch.Tensor(img))

torch_imgs = torch.cat(imgs, dim=3)

means, stdevs = [], []
for i in range(3):
    pixels = torch_imgs[:, :, i, :]  # 拉成一行
    means.append(torch.mean(pixels))
    stdevs.append(torch.std(pixels))

# cv2 读取的图像格式为BGR,PIL/Skimage读取到的都是RGB不用转
means.reverse()  # BGR --> RGB
stdevs.reverse()

print("normMean = {}".format(means))
print("normStd = {}".format(stdevs))

  

第二种写法,读一张算一张,比较耗时:先过一遍计算出均值,再过一遍计算出方差。

import os
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread

startt = 4000
CNum = 1000   # 挑选多少图片进行计算
num = 1000 * 3200 * 1800  # 这里(3200,1800)是每幅图片的大小,所有图片尺寸都一样

imgs=[]
R_channel = 0
G_channel = 0
B_channel = 0
for i in range(startt, startt+CNum):
    img = imread(os.path.join(root_path, filename[i]))
    R_channel = R_channel + np.sum(img[:, :, 0])
    G_channel = G_channel + np.sum(img[:, :, 1])
    B_channel = B_channel + np.sum(img[:, :, 2])

R_mean = R_channel / num
G_mean = G_channel / num
B_mean = B_channel / num

R_channel = 0
G_channel = 0
B_channel = 0
for i in range(startt, startt+CNum):
    img = imread(os.path.join(root_path, filename[i]))
    R_channel = R_channel + np.sum(np.power(img[:, :, 0]-R_mean, 2) )
    G_channel = G_channel + np.sum(np.power(img[:, :, 1]-G_mean, 2) )
    B_channel = B_channel + np.sum(np.power(img[:, :, 2]-B_mean, 2) )

R_std = np.sqrt(R_channel/num)
G_std = np.sqrt(G_channel/num)
B_std = np.sqrt(B_channel/num)

# R:65.045966   G:70.3931815    B:78.0636285
print("R_mean is %f, G_mean is %f, B_mean is %f" % (R_mean, G_mean, B_mean))
print("R_std is %f, G_std is %f, B_std is %f" % (R_std, G_std, B_std))

  

猜你喜欢

转载自www.cnblogs.com/liugl7/p/10874958.html