用python写一个opencv用svm+bog训练识别图片火焰模型的代码,并在测试这个模型是进行非极大值抑制
时间: 2024-05-15 21:14:54 浏览: 115
由于没有提供数据集,以下代码仅为参考示例。
```
import cv2
import numpy as np
# 读取数据集
data = []
labels = []
for i in range(1, 11):
img_fire = cv2.imread(f"fire_{i}.jpg", 0)
img_fire = cv2.resize(img_fire, (64, 64))
hog = cv2.HOGDescriptor((64, 64), (16, 16), (8, 8), (8, 8), 9)
data.append(hog.compute(img_fire))
labels.append(1)
img_non_fire = cv2.imread(f"non_fire_{i}.jpg", 0)
img_non_fire = cv2.resize(img_non_fire, (64, 64))
data.append(hog.compute(img_non_fire))
labels.append(-1)
# 转换为numpy数组
data = np.array(data, dtype=np.float32)
labels = np.array(labels, dtype=np.int32)
# 训练SVM模型
svm = cv2.ml.SVM_create()
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.setType(cv2.ml.SVM_C_SVC)
svm.setC(0.01)
svm.train(data, cv2.ml.ROW_SAMPLE, labels)
# 测试模型
img_test = cv2.imread("test.jpg", 0)
img_test = cv2.resize(img_test, (800, 600))
hog = cv2.HOGDescriptor((64, 64), (16, 16), (8, 8), (8, 8), 9)
features = hog.compute(img_test)
result = svm.predict(features)
result = result[1][0]
print("火焰" if result == 1 else "非火焰")
# 非极大值抑制
boxes = []
for i in range(0, img_test.shape[0] - 64, 8):
for j in range(0, img_test.shape[1] - 64, 8):
patch = img_test[i:i+64, j:j+64]
features = hog.compute(patch)
result = svm.predict(features)
if result == 1:
boxes.append((j, i, j+64, i+64))
nms_boxes = cv2.dnn.NMSBoxes(boxes, [1.0], 0.5, 0.3)
for i in nms_boxes:
x1, y1, x2, y2 = boxes[i[0]]
cv2.rectangle(img_test, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.imshow("result", img_test)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文