下面介紹第一個影響重大的基於深度學習的目標檢測算法R-CNN,自2012年AlexNet網絡在ImageNet上大放異彩之後,很多領域逐漸引入了深度學習特別是深度卷積神經網絡的方法。2013年首次將深度卷積神經網絡引入目標檢測領域的算法是OverFeat算法,出自論文《OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks》,它基於AlexNet卷積神經網絡,實現了識別、定位、檢測共用同一個網絡框架,獲得了2013年ILSVRC定位比賽的冠軍。在2014年提出的目標檢測算法R-CNN真正引起世人對深度學習目標檢測的注意,而且R-CNN的性能遠遠優於OverFeat,因此但不道德的默認R-CNN算法是深度學習目標檢測算法的開山之作。R-CNN出自論文《Rich feature hierarchies for accurate object detection and semantic segmentation》。
使用了 region proposals 的方法和convolutional neural networks卷積神經網絡,即 Regions with CNN features,簡稱R-CNN。
第一步:在一張輸入圖像上使用selective search算法生成1k~2k個候選區域region proposals。
第二步:在每個候選區域region proposal上使用深度卷積神經網絡,這裡使用的就是AlexNet,進行特徵提取,得到特徵向量。
第三步:將提取到的特徵向量分別送到每個類別的SVM分類器,判斷是否屬於該類別。
第四步:經過前三步能夠選擇出最好的候選區域region proposal,但是selective search算法可能生成的選區域region proposals不是特別的準確,所以在這一步通過回歸器對候選區域region proposal坐標進行修正。
selective search算法的python代碼
pip install selective-searchfrom selective_search import selective_searchimport cv2
image = cv2.imread("./dog.jpg")boxes = selective_search(image, mode='single', random_sort=False)
print(boxes)for x0, y0, x1, y1 in boxes: cv2.rectangle(image, (x0, y0), (x1, y1), (255, 0, 0), 1)
cv2.imshow("image", image)cv2.waitKey(0)
再來看看另一個selective search算法的python包selectivesearch,安裝和使用命令如下。
pip install selectivesearchfrom selectivesearch import selectivesearch
import cv2
image = cv2.imread("./dog.jpg")boxes = selectivesearch.selective_search(image, scale=500, sigma=0.6, min_size=50)
for r in boxes[1]: cv2.rectangle(image, (r["rect"][0], r["rect"][1]), (r["rect"][2], r["rect"][3]), (255, 0, 0), 1)
cv2.imshow("image", image)cv2.waitKey(0)
第二種方法是使用opencv-contrib-python,opencv圖像處理庫中帶有selective search算法的實現。安裝和舉例如下,下圖是間隔100個區域繪製的結果。從繪製效果和運行速度上看,opencv中的selective search都是最好的,所以推薦使用opencv。另外opencv由於對算法性能進行了優化在工業上應用廣泛,唯一存才的問題是有些版本變動和不兼容。
pip install opencv-contrib-python==3.4.3.18import randomimport timeimport cv2
image = cv2.imread("./dog.jpg")ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()ss.setBaseImage(image)
method = "fast"
if method == "fast": ss.switchToSelectiveSearchFast()elif method == "quality": ss.switchToSelectiveSearchQuality()
start = time.time()rects = ss.process()end = time.time()
print("[INFO] selective search took {:.4f} seconds".format(end - start))print("[INFO] {} total region proposals".format(len(rects)))
for i in range(0, len(rects), 100):
output = image.copy() for (x, y, w, h) in rects[i:i + 100]: color = [random.randint(0, 255) for j in range(0, 3)] cv2.rectangle(output, (x, y), (x + w, y + h), color, 2)
cv2.imshow("Output", output) key = cv2.waitKey(0) & 0xFF if key == ord("q"): break