存在一个文件夹,其中放着若干图像,现在想对这些图像,根据其明亮程度进行分类,分为10类(0-9),将图像自动移动到对应的类别中;
其中涉及:
1)读取图像的Y-U-V值,其中Y值代表图像的亮度;
2)python中的文件读写操作;
3)使用shutil进行文件的移动;# 这部分的代码可以参考用于文件的移动;可以处理其他任务;
以下是代码部分:
import os
import sys
import cv2
import shutil
def getTheBright(path):
"""
求取图像的亮度值
:param path: 输入图像路径
:return: 返回该图像亮度值
"""
img=cv2.imread(path)
b, g, r = cv2.split(img)
avg_b = 0
avg_g = 0
avg_r = 0
sum_b = 0
sum_g = 0
sum_r = 0
for i in range(0, b.shape[0]):
for j in range(0, b.shape[1]):
sum_b += b[i][j]
sum_g += g[i][j]
sum_r += r[i][j]
avg_b = int(sum_b/b.shape[0]/b.shape[1])
avg_g = int(sum_g/g.shape[0]/g.shape[1])
avg_r = int(sum_r/r.shape[0]/r.shape[1])
y = int(0.3*avg_r+0.59*avg_g+0.11*avg_b)
return y
def getTheYvalue():
"""
获得文件夹下所有图像的Y值
:return:
"""
original_path = "./illumination_test_images/"
files = os.listdir(original_path)
all_Y = []
fp = open("./illumination-level.txt", "w")
for i in range(0, len(files)):
y = getTheBright(original_path+files[i])
print(y)
all_Y.append(y)
fp.write(str(y)+"\n")
fp.close()
def readTextGetYvalue():
"""
得到txt文件中的所有Y值
:return:
"""
fp = open("./illumination-level.txt","r+")
Y = fp.readlines()
y_value = []
for line in Y:
line = line.rstrip("\n")
y_value.append(int(line))
print(y_value)
max_y = max(y_value)
min_y = min(y_value)
print(max_y)
print(min_y)
for i in range(len(y_value)):
y_value[i] = int((y_value[i]-min_y)/(max_y-min_y)*10)
print(y_value)
return y_value
def moveTheOriImageToRightIllumination():
"""
根据illumination-level.txt中的结果将illumination_test_images中的图像分配到0-10种亮度等级中
:return:
"""
y_value = readTextGetYvalue()
ori_path = "./illumination_test_images/"
dst_path = "./results/"
img_files = os.listdir(ori_path)
for i in range(0, len(y_value)):
print(i)
shutil.copy(ori_path+img_files[i], dst_path+str(y_value[i]))
if __name__ == '__main__':
"""
This .py is uesd to classify the dataset with its illumination levels.
"""
getTheYvalue() # 获取图像亮度,写入illumination-level.txt
# moveTheOriImageToRightIllumination() # 移动图像
说明:
先运行getTheYvalue()函数,然后再运行moveTheOriImageToRightIllumination()函数;
需要准备文件夹:
1)illumination_test_images:存放着需要处理的全部图像;
2)illumination-level.txt:将每张图像的Y值进行存储;
3)results中存放分类后的图像,results中包含0-9这10个文件夹,每个文件夹中存放对应的分类后的图像;