opencv 3.0 DPM Cascade 检测 (附带TBB和openMP加速)
时间: 2024-02-05 20:14:10 浏览: 164
DPM(Deformable Part-based Model) Cascade是一种常用的目标检测算法,在OpenCV 3.0中已经支持。在DPM Cascade中,目标被分为多个部分,每个部分用一个分类器来检测,这些分类器被组成一个级联分类器,来提高检测速度和准确率。
TBB和OpenMP是常用的多线程库,可以加速DPM Cascade的检测。在使用TBB和OpenMP之前,需要先安装它们。在Linux系统中,可以通过以下命令安装:
```
sudo apt-get install libtbb-dev
sudo apt-get install libomp-dev
```
在Windows系统中,可以在Intel官网下载TBB和OpenMP的安装程序进行安装。
下面是基于OpenCV 3.0的DPM Cascade检测代码,附带TBB和OpenMP加速:
```python
import cv2
import numpy as np
# 加载级联分类器
cascade = cv2.CascadeClassifier('path/to/cascade.xml')
# 加载图像
img = cv2.imread('path/to/image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测目标
rects = cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
# 绘制矩形框
for (x, y, w, h) in rects:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
加入TBB和OpenMP加速的代码如下:
```python
import cv2
import numpy as np
import time
import threading
import multiprocessing
# 加载级联分类器
cascade = cv2.CascadeClassifier('path/to/cascade.xml')
# 加载图像
img = cv2.imread('path/to/image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测目标
start_time = time.time()
rects = cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
end_time = time.time()
print('串行检测时间:', end_time-start_time)
# 绘制矩形框
for (x, y, w, h) in rects:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# TBB并行检测
def detect_with_tbb(gray, cascade):
rects = cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
return rects
start_time = time.time()
tbb_results = []
tbb = threading.Thread(target=tbb_results.append, args=(detect_with_tbb(gray, cascade),))
tbb.start()
tbb.join()
end_time = time.time()
print('TBB检测时间:', end_time-start_time)
# 绘制矩形框
for (x, y, w, h) in tbb_results[0]:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# OpenMP并行检测
def detect_with_omp(gray, cascade):
rects = cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
return rects
start_time = time.time()
omp_results = []
omp = multiprocessing.Process(target=omp_results.append, args=(detect_with_omp(gray, cascade),))
omp.start()
omp.join()
end_time = time.time()
print('OpenMP检测时间:', end_time-start_time)
# 绘制矩形框
for (x, y, w, h) in omp_results[0]:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上面的代码中,我们使用了Python的多线程库threading和多进程库multiprocessing来实现TBB和OpenMP的并行化。通过比较串行检测时间和并行检测时间,可以看出TBB和OpenMP都可以有效地加速DPM Cascade的检测。
阅读全文