C++和Python中的轮廓差异

6 投票
1 回答
706 浏览
提问于 2025-04-18 09:18

我现在正在使用opencv来检测形状的简单轮廓。最开始,我用的是c++,一切都运行得很好。现在,我想用Python来做同样的事情,因为我需要在网上使用,但轮廓检测似乎没有那么好。

这是我的c++代码:

_src = cv::imread(_imagePath);
cv::Mat gray;
cv::cvtColor(_src, gray, CV_BGR2GRAY);
cv::Mat bw;
cv::Canny(gray, bw, 0, 50, 5);
cv::findContours(bw.clone(), allCountours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

如你所见,这段代码很简单,Python中的代码是:

self._src = cv2.imread(self._imagePath)
gray = cv2.cvtColor(self._src, cv2.COLOR_BGR2GRAY)
bw = cv2.Canny(gray, 0, 50, 5)
allCountours, hierarchy = cv2.findContours(bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

为了展示结果,我用随机颜色在不同的轮廓上绘制了轮廓:

在这里输入图片描述

从图中可以看出,在c++中,每个形状的轮廓都被正确检测到了,虽然不是完美的,而在Python中,我检测到了更多的轮廓。每当一条线稍微断开一点,就会检测到一个新的轮廓。你有什么建议可以解决这个问题吗?谢谢!

1 个回答

2

C++中的函数格式是这样的: void Canny(InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false )

而在Python中,它是: cv.Canny(image, edges, threshold1, threshold2, aperture_size=3) → None

你可以看到,Python版本的最后一个参数没有了。这个参数可能默认是设置为 true。你可以试试看吗?

撰写回答