目標:
有五種水質的圖片,水質等級分1~5級,根據這些圖片,構建一個分類系統,對新資料進行分類,
注:資料集中每個圖片的命名方式都為‘水質級別_序號’
思路:
圖片同一個位置上有R,G,B三個像素值,將樣本圖片裁切為100*100統一大小的圖片,每個像素點的每個顏色通道都作為特征,使用顏色矩來表示特征,
特征提取:
1. 將每個像素點的每個顏色通道都作為特征,100 * 100 * 3
2. 使用顏色矩
顏色矩是一種簡單粗暴的顏色特征表示方法
一階顏色矩:(均值,表示圖片的明亮程度)
二階顏色矩:(標準差,表示顏色的分布)
三階顏色矩:(標準差再開根)

資料集:
未處理:

經過處理后:

處理方式:
使用Image.crop()方法對圖片進行切割,用法如下:
Image.crop(left, up, right, below)
- left:與左邊界的距離
- up:與上邊界的距離
- right:還是與左邊界的距離
- below:還是與上邊界的距離
代碼:
'''
@Author : "HCL"
'''
from PIL import Image
import os
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
"""切分影像"""
# dir_list = r'F:\PythonProject\water_test\images'
# cut_img_path = r'F:\PythonProject\water_test\cut_img'
# # 遍歷影像檔案
# for file in os.listdir(dir_list):
# # print(file)
# # 拼接檔案路徑
# img_path = os.path.join(dir_list, file)
# # 創建Image物件
# img = Image.open(img_path)
# # 獲取圖片大小
# x, y = img.size
# # 切分圖片
# cut_img = img.crop((x / 2, y / 2, x / 2 + 100, y / 2 + 100))
# # 保存切分后的圖片
# cut_img.save(os.path.join(cut_img_path, file))
"""水質檢測"""
# 獲取處理好的圖片資料集
cut_path = r'F:\PythonProject\water_test\cut_img'
datas = []
Y = []
X = []
# 遍歷影像
for file in os.listdir(cut_path):
# 創建image物件
img = Image.open(os.path.join(cut_path, file))
# 獲取r,g,b
r_img, g_img, b_img = img.split()
r_datas = np.array(r_img)
g_datas = np.array(g_img)
b_datas = np.array(b_img)
# 計算一階顏色矩
r1 = r_datas.mean()
g1 = g_datas.mean()
b1 = b_datas.mean()
# 計算二階顏色矩
r2 = r_datas.std()
g2 = g_datas.std()
b2 = b_datas.std()
# 計算三階顏色矩
r3 = (((r_datas - r1) ** 3).mean()) ** 1 / 3
g3 = (((g_datas - g1) ** 3).mean()) ** 1 / 3
b3 = (((b_datas - b1) ** 3).mean()) ** 1 / 3
X.append([r1, g1, b1, r2, g2, b2, r3, g3, b3])
# 資料集中每個圖片的命名方式都為‘水質級別_序號’
Y.append(file.split('_')[0])
X = np.array(X)
# 特征矩陣大小
# print(X.shape)
# 切分資料集
train_X, test_X, train_Y, test_Y = train_test_split(X, Y)
# KNN演算法
s = KNeighborsClassifier()
# 訓練
s.fit(train_X, train_Y)
# 輸出評分
print(s.score(test_X, test_Y))
專案鏈接(阿里云盤分享)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/385448.html
標籤:其他
上一篇:OWOD訓練運行教程
下一篇:實戰內容(13)- Invalid audio stream. Exactly one MP3 audio stream is required.
