无法找到正确数量的轮廓计数

我正在尝试查找具有红色轮廓的特定轮廓。以下是我在此图像上尝试的代码 image

import numpy as npimport cv2image = cv2.imread('C:/Users/htc/Desktop/image.png')original = image.copy()image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)lower = np.array([0,50,50], dtype="uint8")upper = np.array([10, 255,255], dtype="uint8")mask = cv2.inRange(image, lower, upper)# Find contourscnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# Extract contours depending on OpenCV versioncnts = cnts[0] if len(cnts) == 2 else cnts[1]print(len(cnts))# Iterate through contours and filter by the number of vertices for c in cnts:    perimeter = cv2.arcLength(c, True)    approx = cv2.approxPolyDP(c, 0.04 * perimeter, True)    if len(approx) > 5:        cv2.drawContours(original, [c], -1, (36, 255, 12), -1)cv2.imshow('mask', mask)cv2.imshow('original', original)cv2.waitKey()

输出output

我得到的轮廓长度是14,这是不正确的。正确的输出应该是3。我哪里做错了?


回答:

如果你能注意到,由于你的掩模图像中有断开之处,导致检测到了许多轮廓。为了纠正这一点(如果你只需要计数),你可以在查找轮廓之前对获得的掩模图像进行膨胀处理,如下所示。

mask = cv2.inRange(image, lower, upper)# Dilating the maskkernel = np.ones((3, 3), dtype=np.uint8)mask = cv2.dilate(mask, kernel, iterations=2)# Find contourscnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注