计算图像数据集的RGB均值
最近在跑代码的时候,需要用到RGB三个通道上的均值,如下图所示:
写了一个程序,如下:
import os
import cv2
import random
import numpy as np
#数据集的位置
dataset_dir = 'data'
# 验证集图像数量
_NUM_VALIDATION = 1000
# 随机种子
_RANDOM_SEED = 0
def _get_filenames_and_classes(dataset_dir):
"""Returns a list of filenames and inferred class names.
Args:
dataset_dir:A directory containing a set of different datasets.Each dataset
contains a set of subdirectories representing class names.Each subdirectory
should contain PNG or JPG encoded images.
Returns:
A list of image file paths, relative to `dataset_dir` and the list of
subdirectories, representing class names.
"""
flower_root = os.path.join(dataset_dir, 'Stripe')
directories = []
class_names = []
for filename in os.listdir(flower_root):
path = os.path.join(flower_root, filename)
if os.path.isdir(path):
directories.append(path)
class_names.append(filename)
photo_filenames = []
for directory in directories:
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
photo_filenames.append(path)
# Divide into train and test:
random.seed(_RANDOM_SEED)
random.shuffle(photo_filenames)
training_filenames = photo_filenames[_NUM_VALIDATION:]
#validation_filenames = photo_filenames[:_NUM_VALIDATION]
return training_filenames
def compute(file_names):
per_image_Rmean = []
per_image_Gmean = []
per_image_Bmean = []
for file_name in file_names:
img = cv2.imread(file_name, 1)
per_image_Rmean.append(np.mean(img[:,:,0]))
per_image_Gmean.append(np.mean(img[:,:,1]))
per_image_Bmean.append(np.mean(img[:,:,2]))
R_mean = np.mean(per_image_Rmean)
G_mean = np.mean(per_image_Gmean)
B_mean = np.mean(per_image_Bmean)
return R_mean, G_mean, B_mean
if __name__ == '__main__':
photo_filenames = _get_filenames_and_classes(dataset_dir)
R, G, B= compute(photo_filenames)
print(R, G ,B)
注释:
目录结构如下所示:
data(放数据集的地方)
cifar10(数据集)
airplane
.....
Stripe(数据集)
defect
normal