赞
踩
- # PIL - Image: python呈像库
- from PIL import Image
- import numpy as np
- import os
- import re
- def myMain():
-
- # 1.获取图片名称
- path = "./images/images/"
- imgNames = getName(path)
-
- # 2.加载图片
- data, labels = load_Img(path, imgNames)
-
- np.save("water_data.npy", data)
- np.save("water_labels.npy", labels)
- def getName(path):
- """
- 批量读取图片名称
- :param imgDir: 图片所在路径
- :param imgName: 图片名称
- :return: 图片名称列表
- """
- filenames = os.listdir(path)
-
- # Return a list of all non-overlapping matches in the string
- # def findall(pattern, string, flags=0)
- # pattern:待查找文件名称
- # string:查找位置
- imgNames = []
-
- for i in filenames:
- name = re.findall(r"\b\d_\d+\.jpg", i)
- imgNames.extend(name) # 直接添加元素
- return imgNames
- def imgToArray(r, g, b):
- """
- 将图片转换为数组
- :param r: 红
- :param g: 绿
- :param b: 蓝
- :return: 数组
- """
- return [np.asarray(r), np.asarray(g), np.asarray(b)]
- def Var(rd=None, gd=None, bd=None):
- """
- 求图片的颜色距
- :param rd: 三基色
- :return: 三阶颜色距
- """
- r1 = np.mean(rd) # 一阶颜色距
- r2 = np.mean(gd) # 一阶颜色距
- r3 = np.mean(bd) # 一阶颜色距
- s4 = np.std(rd) # 二阶颜色距
- s5 = np.std(gd) # 二阶颜色距
- s6 = np.std(bd) # 二阶颜色距
- t1 = np.mean((rd - rd.mean())**3)
- t2 = np.mean((gd - gd.mean())**3)
- t3 = np.mean((bd - bd.mean())**3)
- return [r1, r2, r3, s4, s5, s6, np.sign(np.mean(t1)*abs(t1)**(1/3)), np.sign(np.mean(t2)*abs(t2)**(1/3)), np.sign(np.mean(t3)*abs(t3)**(1/3))]
- def load_Img(path, fileNameList):
- """
- 加载图片,并预处理
- :param fileNameList:
- :return:
- """
- n = len(fileNameList) # 获取图片数量
- data = np.zeros([n, 9]) # 样本自变量
- labels = np.zeros([n]) # 样本标签
-
- # 遍历每一张图片
- imgList = []
- for i in range(n):
- img = Image.open(path+fileNameList[i])
- M, N = img.size
- img = img.crop((M/2-50,N/2-50,M/2+50,N/2+50)) # 选取图片中心位置
-
- r, g, b = img.split() # 将颜色通道分开
-
- img_list = imgToArray(r, g, b) # 将图片转换为数组
- for j in range(9):
- data[i, j] = Var(img_list[0], img_list[1], img_list[2])[j]
- labels[i] = fileNameList[i][0] # 存储图片标签
-
- return data, labels
- import numpy as np
- from sklearn.tree import DecisionTreeClassifier
- from sklearn.model_selection import train_test_split
- from sklearn import metrics
-
-
- data = np.load("water_data.npy")
- labels = np.load("water_labels.npy")
-
- data_tr, data_te, target_tr, target_te = train_test_split(data, labels, test_size=0.2, random_state=10)
-
- model = DecisionTreeClassifier(random_state=10).fit(data_tr, target_tr)
-
- res = model.predict(data_te)
-
- pre = model.score(data_te, target_te)
-
- print(target_te)
- print(res)
-
- # 精度
- print(sum(res==target_te)/len(res))
- print(pre)
-
- # 报告
- print(metrics.classification_report(target_te, res))
- print(metrics.confusion_matrix(target_te, res))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。