我想使用选择性搜索算法将图像分割成可能的对象位置。我发现我已经用于计算机视觉的库OpenCV实现了这个功能,如文档here所示。但是,我使用的是Python而不是C ++,所以我查看了OpenCV的github存储库,直到找到我在下面复制的example。
#!/usr/bin/env python
'''
A program demonstrating the use and capabilities of a particular image segmentation algorithm described
in Jasper R. R. Uijlings, Koen E. A. van de Sande, Theo Gevers, Arnold W. M. Smeulders:
"Selective Search for Object Recognition"
International Journal of Computer Vision, Volume 104 (2), page 154-171, 2013
Usage:
./selectivesearchsegmentation_demo.py input_image (single|fast|quality)
Use "a" to display less rects, 'd' to display more rects, "q" to quit.
'''
import cv2
import sys
if __name__ == '__main__':
img = cv2.imread(sys.argv[1])
cv2.setUseOptimized(True)
cv2.setNumThreads(8)
gs = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()
gs.setBaseImage(img)
if (sys.argv[2][0] == 's'):
gs.switchToSingleStrategy()
elif (sys.argv[2][0] == 'f'):
gs.switchToSelectiveSearchFast()
elif (sys.argv[2][0] == 'q'):
gs.switchToSelectiveSearchQuality()
else:
print(__doc__)
sys.exit(1)
rects = gs.process()
nb_rects = 10
while True:
wimg = img.copy()
for i in range(len(rects)):
if (i < nb_rects):
x, y, w, h = rects[i]
cv2.rectangle(wimg, (x, y), (x+w, y+h), (0, 255, 0), 1, cv2.LINE_AA)
cv2.imshow("Output", wimg);
c = cv2.waitKey()
if (c == 100):
nb_rects += 10
elif (c == 97 and nb_rects > 10):
nb_rects -= 10
elif (c == 113):
break
cv2.destroyAllWindows()
不幸的是,使用命令python selective_search.py "/home/christopher/DroneKit/Vision/Face Detection/Annotated Faces in the Wild/originalPics/2002/07/19/big/img_135.jpg" f
运行此程序会出现以下错误:
Traceback (most recent call last):
File "selective_search.py", line 37, in <module>
rects = gs.process()
TypeError: Required argument 'rects' (pos 1) not found
根据该错误消息,我想也许我可以将它传递给Python列表,然后底层的C ++函数会用算法的输出填充它。但是,当我执行以下代码时:
rects = []
gs.process(rects)
print(rects)
输出为空列表,显示的图像上没有绘制矩形。因此,我对如何拨打gs.process()
感到茫然。如果有帮助,函数的C ++声明是
CV_WRAP virtual void process(CV_OUT std::vector<Rect>& rects) = 0;
(编辑)从评论中复制的其他信息:
help(gs.process)
的输出:
process(...) method of cv2.ximgproc_segmentation_SelectiveSearchSegmentation instance process(rects) -> None. rects = gs.process(rects) just makes rects None and causes the program to terminate with an exception
使用rects = gs.process(rects)
设置rects到None
并导致程序以异常终止。
OpenCV版本是3.2.0。
使用numpy数组而不是python列表会崩溃我的程序,并显示以下消息:
OpenCV Error: Assertion failed (channels() == CV_MAT_CN(dtype)) in copyTo, file /home/christopher/opencv/modules/core/src/copy.cpp, line 259
terminate called after throwing an instance of 'cv::Exception'
what(): /home/christopher/opencv/modules/core/src/copy.cpp:259: error: (-215) channels() == CV_MAT_CN(dtype) in function copyTo
Aborted (core dumped)
答案 0 :(得分:0)
显然,我为Python编译的OpenCV 3.2.0版本在本地缺少此fix。我继续使用OpenCV 3.3.0的latest stable release重新编译我的python绑定,并对OpenCV contrib存储库进行了最新更改,之后示例脚本按预期工作。