import cv2 |
#环境python3、opencv3 |
#导入需要使用的库 |
import numpy as np |
import matplotlib.pyplot as plt |
#读取npy文件 |
samples = np.load( "animals.npy" ) |
labels = np.load( "labels.npy" ) |
#将numpy数组转换为图像并显示出来 |
def show_image_plt(img_data): |
plt.imshow(img_data) |
plt.show() |
#显示出前10个图像 |
for i in range ( 10 ): |
show_image_plt(samples[i]) |
#定义样本特征工程并处理 |
samples_feature = [] |
for sample in samples: |
#用高斯滤波处理 |
sample = cv2.GaussianBlur(sample,( 3 , 3 ), 0 , 0 ) |
#用sobel算子进行边缘检测 |
sobel_x = cv2.Sobel(sample,cv2.CV_64F, 1 , 0 ,ksize = 3 ) #(图像,深度,x方向的阶数,y方向的阶数,卷积核大小) |
sobel_y = cv2.Sobel(sample,cv2.CV_64F, 0 , 1 ,ksize = 3 ) |
sobel_xy = np.sqrt(np.square(sobel_x) + np.square(sobel_y)) |
#将处理后的图像展平 |
sample_feature = np.reshape(sobel_xy,( - 1 )).tolist() |
samples_feature.append(sample_feature) |
#数据标准化 |
from sklearn.preprocessing import StandardScaler |
sc = StandardScaler() |
sc.fit_transform(samples_feature) |
#利用支持向量机构建分类模型 |
from sklearn import svm |
clf = svm.SVC() |
#用所有的样本数据进行模型训练 |
clf.fit(samples_feature,labels) |
#查看训练好的模型预测准确率 |
print ( "准确率:" ,clf.score(samples_feature,labels)) |
#预测新图像 |
test_sample = cv2.imread( "test_animals.jpg" ) |
#用高斯滤波处理 |
test_sample = cv2.GaussianBlur(test_sample,( 3 , 3 ), 0 , 0 ) |
#用sobel算子进行边缘检测 |
sobel_x = cv2.Sobel(test_sample,cv2.CV_64F, 1 , 0 ,ksize = 3 ) |
sobel_y = cv2.Sobel(test_sample,cv2.CV_64F, 0 , 1 ,ksize = 3 ) |
sobel_xy = np.sqrt(np.square(sobel_x) + np.square(sobel_y)) |
#将处理后的图像展平 |
test_sample_feature = np.reshape(sobel_xy,( - 1 )) |
#用训练好的模型预测新图像 |
prediction = clf.predict([test_sample_feature]) |
print ( "预测结果:" ,prediction) |