有的图虽然是三通道的,但其实是灰度模式,即三通道RBG相等
import cv2
import os
import numpy as np
def file_name(file_dir):
"""
该函数的作用:获取file_dir文件夹下所有图片地址
:param file_dir: 文件目录
:return: 返回图片地址列表
"""
L = []
for root, dirs, files in os.walk(file_dir):
for file in files:
# 其中os.path.splitext()函数将路径拆分为文件名+扩展名
if os.path.splitext(file)[1] == '.png':
L.append(os.path.join(root, file))
return L
def img_color(src):
"""
判断图像是彩图还是三通道灰度模式图
:param src:
:return:
"""
h, w, c = src.shape[:] # hwc
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) # 灰度图
img = np.empty(shape=(h, w, c), dtype=np.uint8) # 创建空白模板
# 三通道灰度模式图,即三通道RGB值相等
for ch in range(c):
img[:, :, ch] = gray
# 判断是否为彩色图像,是则返回1,否则返回0
if (src != img).sum() !=0 :
# if (src == img).all() == 0:
# print("color")
return 1
else:
# print("gray")
return 0
# 输出列表中所有彩图序号
path = './2020'
L = file_name(path)
list = []
for i in L:
src = cv2.imread(i) # 原图
if img_color(src) ==1:
# print(i)
if len(i) == 42:
list.append(int(i[37:38]))
# print(i[37:38])
elif len(i) == 43:
list.append(int(i[37:39]))
# print(i[37:39])
elif len(i) == 44:
list.append(int(i[37:40]))
# print(i[37:40])
list.sort()
print(list)
cv2.waitKey(0)
cv2.destroyAllWindows()