import cv2
import matplotlib.pyplot as plt
import os
import numpy as np
# 计算方差
def getss(list):
# 计算平均值
avg = sum(list) / len(list)
# 定义方差变量ss,初值为0
ss = 0
# 计算方差
for l in list:
ss += (l - avg) * (l - avg) / len(list)
# 返回方差
return ss
# 获取每行像素平均值
def getdiff(img):
# 定义边长
Sidelength = 8
# 缩放图像
img = cv2.resize(img, (Sidelength, Sidelength), interpolation=cv2.INTER_CUBIC)
# 灰度处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# avglist列表保存每行像素平均值
avglist = []
# 计算每行均值,保存到avglist列表
for i in range(Sidelength):
avg = sum(gray[i]) / len(gray[i])
avglist.append(avg)
# 返回avglist平均值
return avglist
# 读取测试图片
list_name = os.listdir('photo1')
for word in list_name:
path = os.getcwd() + '\\photo1\\' + word
# print(path)
for dirpath, dirnames, filenames in os.walk(path): # 目录路径,目录名称,文件名称(全称)
list = []
for filename in filenames: # 遍历主文件夹下所有的文件名称,此时filename代表文件名称
path = dirpath + '\\' + filename
print(filename)
# print(type(dirpath + '\\'+filename))
# print(os.path.join(dirpath,filename))
# print(filename)
# img = cv2.imread(path)
img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
# img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1)
gtess = getss(getdiff(img))
list.append(gtess)
print(list)
for i in range(len(list)):
# break
print('i=', i)
# print('i中的list长度:', len(list))
a = []
for j in range(i + 1, len(list) + 1): # 此处列表的长度是实时更新的,range不会随列表元素变化进行更新变化进行实时更新
if len(list) <= j:
print('超出范围!!!!!!!!!!!!!!!')
f=0
for c in range(len(a)):
b = a[c]
print('b====', b)
print('前list:', list)
del list[b-f]
f+=1
print('删除后的list:', list)
break
elif abs(list[i] - list[j]) < 10:
print('有相同的!!')
# 遍历文件夹,删除方差值与列表中的方差值相同的照片
# 遍历文件夹,获取其方差值
for filename in filenames:
print(filename)
path = dirpath + '\\' + filename
img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
gtess = getss(getdiff(img))
# 当检索到的图片方差值等于列表中某个方差时,删除该图片
if gtess == float(list[j]):
os.remove(path)
filenames.remove(filename)
a.append(j) # 这里是为了将已经删除目标文件的列表元素序号加入新列表中,后面进行一次删除
# 若删除一次目标文件就删除一次元素,会出现元素检索时跳项的问题
print('a===', a)
print('删除:', path)
break
else:
continue