OpenCV的findContours不正常 [英] OpenCV findContours are not in order

查看:515
本文介绍了OpenCV的findContours不正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用OpenCV findContours方法时,为什么没有按顺序找到轮廓?

When using OpenCV findContours method, how come the contours are not found in order?

inputImage = cv2.imread("randomImage.jpg",0)

im2, contours, hierarchy = cv2.findContours(inputImage.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

j=1

for cnt in reversed(contours):

    letter = inputImage[y:y+h, x:x+w]
    cv2.imwrite(str(j)+"sub/"+str(k)+'.png', letter) 
    k+=1

输入图像由几个字母组成,例如"abcde".但是,将轮廓保存到文件时,它们以"c","e","d","a","b"之类的随机顺序保存.有什么理由吗?

The input image consists of a few letters, for example "abcde". However, when the contours are saved to file they are saved in a random order like "c", "e", "d", "a", "b". Is there any reason for this?

输出: t,l,h,b,e,r,g,o,e

output: t, l, h, b, e, r, g, o, e

推荐答案

如果您仔细观察了Opencv轮廓层次结构页面,请附加其链接:

If you carefully observe the Opencv Contours hierarchy page, attaching it's link:https://docs.opencv.org/3.4.0/d9/d8b/tutorial_py_contours_hierarchy.html

您会发现,根据层次结构和存储轮廓的使用顺序(在情况下为tlhb ...等)会有所不同,它将先处理没有子对象的轮廓,然后再处理没有孩子的轮廓有个孩子.

You will observe that depending on the hierarchy and that you use the order of contours stored( in you case t l h b ... and so on) will differ.It will treat contours which do not have a child first then the contours that have a child.

但是,如果您选择了一个层次结构(例如RETR_CCOMP),它将开始从最深的轮廓开始到最后没有子轮廓.

But if you chose a hierarchy for example a RETR_CCOMP it will start taking contours from the most depth to contours with no child at last.

如果您选择了RETR_TREE之类的层次结构,则将首先使用具有最大子代数的轮廓.

If you chose hierarchy like RETR_TREE then contour with maximum number of child is taken first.

这就是处理轮廓的方法,而不是根据x,y坐标.如果要输出这样的序列,则应获得一个质心并进行x,y排序.

That is how the contour is treated and not according to x,y coordinates. If you want to output such a sequence you should get a centroid and go for x,y sort.

希望这会有所帮助!

这篇关于OpenCV的findContours不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆