第一种写法,先读进来,再计算。比较耗内存。
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 a

本文介绍了三种使用Python计算图像数据集RGB各通道均值和方差的方法:一次性加载所有图像计算、逐张加载计算和一次遍历计算。分别展示了如何使用cv2、numpy、torch和PIL等库来实现,适用于大量图像的统计处理。
最低0.47元/天 解锁文章
5371

被折叠的 条评论
为什么被折叠?



