首页 > 其他 > 详细

计算图片均值和方差脚本

时间:2019-08-17 19:04:05      阅读:198      评论:0      收藏:0      [点我收藏+]
# coding: utf-8

import numpy as np
import cv2
import random

"""
    随机挑选CNum张图片,进行按通道计算均值mean和标准差std
    先将像素从0~255归一化至 0-1 再计算
"""


train_txt_path = '../../Data/train.txt'

CNum = 2000     # 挑选多少图片进行计算

img_h, img_w = 32, 32
imgs = np.zeros([img_w, img_h, 3, 1])
means, stdevs = [], []

with open(train_txt_path, 'r') as f:
    lines = f.readlines()
    random.shuffle(lines)   # shuffle , 随机挑选图片

    for i in range(CNum):
        img_path = lines[i].rstrip().split()[0]

        img = cv2.imread(img_path)
        img = cv2.resize(img, (img_h, img_w))

        img = img[:, :, :, np.newaxis]
        imgs = np.concatenate((imgs, img), axis=3)
        print(i)

imgs = imgs.astype(np.float32)/255.


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

means.reverse() # BGR --> RGB
stdevs.reverse()

print("normMean = {}".format(means))
print("normStd = {}".format(stdevs))
print('transforms.Normalize(normMean = {}, normStd = {})'.format(means, stdevs))

打印输出:
normMean = [0.49680823, 0.48622987, 0.44980356]
normStd = [0.24765104, 0.24397221, 0.26272318]
transforms.Normalize(normMean = [0.49680823, 0.48622987, 0.44980356], normStd = [0.24765104, 0.24397221, 0.26272318])

所以:
print("normMean = {}".format(means))
print("normStd = {}".format(stdevs))
可以输出list

计算图片均值和方差脚本

原文:https://www.cnblogs.com/yanghailin/p/11369673.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!