MSER是最大稳定极值区域:是对一幅灰度图像(灰度值为0~255)取阈值进行二值化处理,阈值从0到255依次递增。阈值的递增类似于分水岭算法中的水面的上升,随着水面的上升,有一些较矮的丘陵会被淹没,如果从天空往下看,则大地分为陆地和水域两个部分,这类似于二值图像。在得到的所有二值图像中,图像中的某些连通区域变化很小,甚至没有变化,则该区域就被称为最大稳定极值区域。具体算法的原理参考http://blog.csdn.net/zhaocj/article/details/40742191
此刻正在听张学友的歌,所以想到先做一个测试吧:
1、不知道如何修改MSER中的参数,如灰度值的变化量,检测到的组块面积的范围以及最大的变化率,只能使用默认参数如下:
mser = cv2.MSER_create()
最后发现了http://bytedeco.org/javacpp-presets/opencv/apidocs/org/bytedeco/javacpp/opencv_features2d.MSER.html#create-int-int-int-double-double-int-double-double-int-,发现可以酱紫根据自己的图像修改参数:
mser = cv2.MSER_create(_delta=2, _min_area=200, _max_variation=0.7)
2、下图是调用mser后用polylines绘制轮廓的结果:
cv2.polylines(imgContours, hulls, 1, (255, 0, 0))
那如果想要得到外接矩形怎么办?求助万能的百度,给出的解决方案如下:http://www.cnblogs.com/jkmiao/p/6797252.html
mser = cv2.MSER_create()
regions, boxes = mser.detectRegions(gray)
for box in boxes:
x, y, w, h = box
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow("img2", vis)
然而并不能解决问题,在调用mser.detectRegions返回两个函数的时候会报,http://answers.opencv.org/question/139636/want-to-get-area-from-mser-operator/这个帖子也出现了类似的错误:
contours, boxes = mser.detectRegions(imgThreshCopy)
Error:
TypeError: Required argument 'bboxes' (pos 2) not found
受到findcontours绘制外界矩形的启发,因此我尝试了第二种解决方案:
for c in hulls:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(vis, (x, y), (x + w, y + h), (255, 0, 0), 1)
至此完美的解决问题,下面是得到的结果图:
最后贴上完整的代码和运行结果:
#coding:utf-8
import numpy as np
import cv2
import nms
img = cv2.imread('3447976_0.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
vis = img.copy()
orig = img.copy()
mser = cv2.MSER_create()
regions = mser.detectRegions(gray, None)
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
cv2.polylines(img, hulls, 1, (0, 255, 0))
cv2.imshow('img', img)
keep = []
for c in hulls:
x, y, w, h = cv2.boundingRect(c)
keep.append([x, y, x + w, y + h])
cv2.rectangle(vis, (x, y), (x + w, y + h), (255, 255, 0), 1)
print "[x] %d initial bounding boxes" % (len(keep))
cv2.imshow("hulls", vis)
keep2=np.array(keep)
pick = nms.nms(keep2, 0.5)
print "[x] after applying non-maximum, %d bounding boxes" % (len(pick))
# loop over the picked bounding boxes and draw them
for (startX, startY, endX, endY) in pick:
cv2.rectangle(orig, (startX, startY), (endX, endY), (255, 0, 0), 1)
cv2.imshow("After NMS", orig)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:[x] 1795 initial bounding boxes
[x] after applying non-maximum, 130 bounding boxes
可以看到应用NMS之前检测到的矩形框是1795个,应用NMS后矩形框的数量减少到了130个,这张图只是拿来做测试用,并没有调整自己的参数,用了默认值。效果还不错吧!