本篇文章介绍一个简单实用的工具包,主要用于 Opencv 中需要对提取到的轮廓进行排序
例如:从左向右,从上到下
示例图:
图像中的数字以及信用卡对卡号的轮廓提取都需要用到,因为提取到的轮廓并不是按照一定顺序进行排序的,而是乱序,所以需要进行排序
工具包代码:
#导入opencv库 pip install opencv
import cv2
#参数1:需要排序的轮廓, 参数2:需要排序的方式,例如:left-to-right 从左到右
def sort_contours(cnts, method='left-to-right'):
#reverse=True 从大到小
reverse = False #从小到大
#表示用第一个参数 x坐标值进行排序
i = 0
if method == 'right-to-left' or method == 'bottom-to-top':
reverse = True
if method == 'top-to-bottom' or method == 'bottom-to-top':
#表示用第二个参数 y坐标进行排序
i = 1
#cv2.boundingRect(c) 获取轮廓左上角的坐标及高宽值
bounding_boxes = [cv2.boundingRect(c) for c in cnts] # 用一个最小的矩形, 把找到的形状包起来(x, y, h, w)
# zip将数据打包成元组形式, 例如:a[1],b[1]为一组 zip(*) * 默认将文件解压成列表
# key=lambda b: b[1][i] b[1]表示为对第二个参数即bounding_boxes进行排序 ;b[1][i] 表示对bounding_boxes中的第i个数据进行排序(0对x, 1对y)
(cnts, bounding_boxes) = zip(*sorted(zip(cnts, bounding_boxes), key=lambda b: b[1][i], reverse=reverse))
return cnts, bounding_boxes
只需要传入需要排序的轮廓,以及需要排序的方式即可!