写一个HOG+SVM识别火灾的代码,其中包括训练模型并用模型测试
时间: 2023-05-25 16:01:50 浏览: 112
路标检测与识别(1).rar_SVM准确_SVM准确率_hog svm_hog+SVM_采用hog+SVM对路标进行训练识别
5星 · 资源好评率100%
火灾识别是一个常见的图像分类问题。其中,HOG(Histograms of Oriented Gradients)和SVM(Support Vector Machine)是常用的特征提取和分类算法。以下是使用OpenCV库和Sklearn库实现HOG SVM火灾识别的代码:
首先,我们需要准备训练和测试数据集。假设我们有两个文件夹,分别命名为“火灾”和“非火灾”,并将包含对应类别的图片放入相应的文件夹。我们需要将图片转换为灰度图,并将其调整为相同的大小以便于处理和训练。
```python
import cv2
import numpy as np
import os
pos_folder = "data/pos"
neg_folder = "data/neg"
pos_images = [os.path.join(pos_folder, f) for f in os.listdir(pos_folder)]
neg_images = [os.path.join(neg_folder, f) for f in os.listdir(neg_folder)]
hog = cv2.HOGDescriptor((64,64),(16,16),(8,8),(8,8),9)
```
接下来,我们可以使用HOG描述符来提取特征,并将特征存储在一个特征向量中。我们使用正样本和负样本来训练SVM,并使用Sklearn库中的SVM分类器。
```python
X = []
y = []
for i, image_path in enumerate(pos_images):
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
resized_img = cv2.resize(gray, (64, 64))
feature = hog.compute(resized_img)
X.append(feature)
y.append(1)
for i, image_path in enumerate(neg_images):
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
resized_img = cv2.resize(gray, (64, 64))
feature = hog.compute(resized_img)
X.append(feature)
y.append(0)
X = np.array(X)
y = np.array(y)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
最后,我们训练模型并测试模型性能。
```python
# 训练SVM模型
from sklearn.svm import SVC
clf = SVC(kernel='linear')
clf.fit(X_train, y_train)
# 测试模型性能
from sklearn.metrics import accuracy_score
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
现在我们有一个HOG SVM模型,可以用它来识别火灾。我们只需要提取测试图片的HOG特征,并使用训练好的SVM分类器进行分类即可。
```python
test_image = cv2.imread("data/test.jpg")
gray = cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY)
resized_img = cv2.resize(gray, (64, 64))
feature = hog.compute(resized_img)
prediction = clf.predict(feature.reshape(1, -1))[0]
if prediction == 1:
print("Fire detected")
else:
print("No fire detected")
```
以上就是HOG SVM识别火灾的完整代码。
阅读全文