如何使用OpenCV进行物体轮廓排序

1 引言

在进行图像处理过程中,我们经常会遇到一些和物体轮廓相关的操作,比如求目标轮廓的周长面积等,我们直接使用Opencv的findContours函数可以很容易的得到每个目标的轮廓,但是可视化后, 这个次序是无序的,如下图左侧所示:

在这里插入图片描述
本节打算实现对物体轮廓进行排序,可以实现从上到下排序或者从左倒右排序,达到上图右侧的可视化结果.

闲话少说,我们直接开始吧. 😃

2 举个栗子

2.1 读取图像

首先,我们来读取图像,并得到其边缘检测图,代码如下:

image = cv2.imread(args['image'])
accumEdged = np.zeros(image.shape[:2], dtype='uint8')
for chan in cv2.split(image):
	chan = cv2.medianBlur(chan, 11)
    edged = cv2.Canny(chan, 50, 200)
    accumEdged = cv2.bitwise_or(accumEdged, edged)
cv2.imshow('edge map', accumEdged)

运行结果如下:
在这里插入图片描述
左侧为原图,右侧为边缘检测图.

2.2 获取轮廓

opencv-python中查找图像轮廓的API为:findContours 函数,该函数接收二值图像作为输入,可输出物体外轮廓、内外轮廓等等.

代码如下:

cnts = cv2.findContours(accumEdged.copy(), cv2.RETR_EXTERNAL,  cv2.CHAIN_APPROX_SIMPLE)
cnts = grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
orig = image.copy()
# unsorted
for (i, c) in enumerate(cnts):
    orig = draw_contour(orig, c, i)
cv2.imshow('Unsorted', orig)
cv2.imwrite("./Unsorted.jpg", orig)

运行结果如下:
在这里插入图片描述
需要注意的是,在OpenCV2.X版本,函数findContours返回两个值,函数声明如下:

contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

但是在OpenCV3以上版本,该函数的声明形式如下:

image, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

所以为了适配两种模式,我们实现函数 grab_contours 来根据不同的版本,选择对应的返回轮廓的下标位置,代码如下:

def grab_contours(cnts):
    # if the length the contours tuple returned by cv2.findContours
    # is '2' then we are using either OpenCV v2.4, v4-beta, or
    # v4-official
    if len(cnts) == 2:
        cnts = cnts[0]

    # if the length of the contours tuple is '3' then we are using
    # either OpenCV v3, v4-pre, or v4-alpha
    elif len(cnts) == 3:
        cnts = cnts[1]

    return cnts

2.3 轮廓排序

通过上述步骤,我们得到了图像中的所有物体的轮廓,接下来我们定义函数sort_contours函数来实现对轮廓进行排序操作,该函数接受method参数来实现按照不同的次序对轮廓进行排序,比如从左往右,或者从右往左.

代码如下:

def sort_contours(cnts, method='left-to-right'):
    # initialize the reverse flag and sort index
    reverse = False
    i = 0
    # handle if sort in reverse
    if method == 'right-to-left' or method == 'bottom-to-top':
        reverse = True
    # handle if sort against y rather than x of the bounding box
    if method == 'bottom-to-top' or method == 'top-to-bottom':
        i = 1

    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b: b[1][i], reverse=reverse))
    return (cnts, boundingBoxes)

上述代码的核心思想为先求出每个轮廓的外接矩形框,然后通过对外接框按照x或y坐标排序进而来实现对轮廓的排序.

调用代码如下:

# sorted
(cnts, boundingboxes) = sort_contours(cnts, method=args['method'])
for (i, c) in enumerate(cnts):
    image = draw_contour(image, c, i)
cv2.imshow('Sorted', image)
cv2.waitKey(0)

运行结果如下:

在这里插入图片描述

2.4 其他结果

利用上述代码,我们也可以实现从左往右的排序,如下所示:
在这里插入图片描述

3 总结

本文利用OpenCV实现了对物体轮廓按指定顺序进行排序的功能,并给出了完整的代码示例.

您学废了吗?

在这里插入图片描述
关注公众号《AI算法之道》,获取更多AI算法资讯。


参考

关注公众号,回复 contour,即可获取完整代码。

  • 7
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
要对OpenCV中的轮廓按照周长进行排序,可以按照以下步骤进行操作: 1. 首先,使用OpenCV的`findContours`函数找到图像中的所有轮廓。这个函数会返回一个包含所有轮廓的列表。 2. 接下来,可以使用`arcLength`函数计算每个轮廓的周长。该函数需要传入轮廓的点集和闭合状态(True表示闭合,False表示非闭合)。 3. 将每个轮廓的周长与其对应的轮廓一起存储在一个列表中。 4. 使用Python的`zip`函数将轮廓和周长列表打包在一起。 5. 使用Python的`sorted`函数对打包后的列表进行排序,可以指定按照周长进行升序或降序排序。 6. 最后,可以将排序后的轮廓和周长分开存储在两个不同的列表中,或者直接使用排序后的列表。 下面是一个示例代码: ```python import cv2 # 读取图像并转为灰度图 image = cv2.imread('image.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 寻找轮廓 contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 计算每个轮廓的周长并存储在列表中 perimeters = [cv2.arcLength(contour, True) for contour in contours] # 将轮廓和周长打包在一起并按照周长进行排序 sorted_contours = sorted(zip(contours, perimeters), key=lambda x: x[1], reverse=True) # 分离排序后的轮廓和周长 sorted_contours, sorted_perimeters = zip(*sorted_contours) # 打印排序后的周长 for perimeter in sorted_perimeters: print(perimeter) ``` 这样,你就可以得到按照周长排序后的轮廓列表和对应的周长列表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵卓不凡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值