如何在OpenCV或Emgu CV中检测三角形边缘?

3

enter image description here

我正在使用Emgu CV,想要在图片中检测出两个锐角。首先我将图像转换为灰度,然后调用cvCanny函数,接着再调用FindContours函数,但是只能找到一个轮廓,三角形没有被找到。

代码:

 public static void Do(Bitmap bitmap, IImageProcessingLog log)
    {
        Image<Bgr, Byte> img = new Image<Bgr, byte>(bitmap);
        Image<Gray, Byte> gray = img.Convert<Gray, Byte>();
        using (Image<Gray, Byte> canny = new Image<Gray, byte>(gray.Size))
        using (MemStorage stor = new MemStorage())
        {
            CvInvoke.cvCanny(gray, canny, 10, 5, 3);
            log.AddImage("canny",canny.ToBitmap());

            Contour<Point> contours = canny.FindContours(
             Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
             Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_TREE,
             stor);

            for (int i=0; contours != null; contours = contours.HNext)
            {
                i++;
                MCvBox2D box = contours.GetMinAreaRect();

                Image<Bgr, Byte> tmpImg = img.Copy();
                tmpImg.Draw(box, new Bgr(Color.Red), 2);
                log.AddMessage("contours" + (i) +",angle:"+box.angle.ToString() + ",width:"+box.size.Width + ",height:"+box.size.Height);
                log.AddImage("contours" + i, tmpImg.ToBitmap());
            }
        }
    }
1个回答

6
我不熟悉EmguCV,但是我可以给你提供思路:
你可以按照以下步骤进行操作:
1.使用“split()”函数将图像分成R、G、B三个平面。 2.对于每个平面,应用Canny边缘检测。 3.然后在其中找到轮廓,并使用“approxPolyDP”函数逼近每个轮廓。 4.如果逼近轮廓中的坐标数为3,则很可能是三角形,而这些值对应于三角形的3个顶点。
以下是Python代码:
import numpy as np
import cv2

img = cv2.imread('softri.png')

for gray in cv2.split(img):
    canny = cv2.Canny(gray,50,200)

    contours,hier = cv2.findContours(canny,1,2)
    for cnt in contours:
        approx = cv2.approxPolyDP(cnt,0.02*cv2.arcLength(cnt,True),True)
        if len(approx)==3:
            cv2.drawContours(img,[cnt],0,(0,255,0),2)
            tri = approx

for vertex in tri:
    cv2.circle(img,(vertex[0][0],vertex[0][1]),5,255,-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

以下是蓝色平面的Canny图: enter image description here 以下是最终输出结果,三角形及其顶点分别用绿色和蓝色标示: enter image description here

1
为什么我们需要将图像分成三个通道?在使用Canny算法后,是否在彩色图像上或灰度图像上进行处理不同呢? - Mikos
不需要分割。您只需将其转换为灰度并使用Canny边缘检测器即可。 - Michael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接