如何在 OpenCV Python 中检查图像轮廓是否为凸的?
函数 cv2.isContourConvex() 用于检查曲线(轮廓)是否为凸的。图像中物体的轮廓是沿边界连接所有连续点的曲线,具有相同的颜色或强度。轮廓用于形状分析以及物体检测和识别等。
语法
cv2.isContourConvex() 的语法如下:
cv2.isContourConvex(cnt)
其中,“cnt”是图像中物体轮廓点的 NumPy 数组。如果轮廓 cnt 为凸的,则返回 True,否则返回 False。
步骤
您可以使用以下步骤来检查图像中的轮廓是否为凸的:
导入所需的库。在以下所有 Python 示例中,所需的 Python 库为 OpenCV。确保您已安装它。
import cv2
使用 cv2.imread() 读取输入图像并将其转换为灰度图像。
img = cv2.imread('pentagon.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
对灰度图像应用阈值处理以创建二值图像。
ret,thresh = cv2.threshold(gray,150,255,0)
使用 cv2.findContours() 函数查找图像中的轮廓。
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
使用 cv2.isContourConvex(cnt) 计算凸性。如果轮廓为凸的,则返回 True,否则返回 False。
cnt= contours[0] k = cv2.isContourConvex(cnt)
在输入图像上绘制轮廓。
cv2.drawContours(img, [cnt], -1, (0,255,255), 3)
打印图像中物体轮廓的凸性。
print("Convexity:", k)
让我们通过几个示例来更好地理解。
示例 1
在下面的 Python 示例中,我们检查矩形的轮廓是否为凸的。
import cv2 import numpy as np img1 = np.zeros((350,630,3), dtype=np.uint8) img = img1[100:250, 200:380, :]=255 img = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(img,150,255,0) contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) print("Number of contours:", len(contours)) cnt= contours[0] k = cv2.isContourConvex(cnt) print("Convexity:", k) x, y = cnt[0][0] cv2.drawContours(img1, [cnt], -1, (0,255,255), 3) cv2.putText(img1, f'Convexity:{k}', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2) cv2.imshow("Polylines", img1) cv2.waitKey(0) cv2.destroyAllWindows()
输出
执行后,它将在控制台上生成以下输出:
Number of contours: 1 Convexity: True
并且我们会看到这个窗口,显示输出:

示例 2
在这个 Python 程序中,我们检查图像中星形物体的轮廓的凸性。
import cv2 import numpy as np img1 = cv2.imread('star.png') img = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(img,0,255,0) contours,hierarchy = cv2.findContours(thresh, 1, 2) print("Number of contours:", len(contours)) cnt= contours[0] k = cv2.isContourConvex(cnt) print("Convexity:", k) x, y = cnt[0][0] cv2.drawContours(img1, [cnt], -1, (0,255,255), 3) cv2.putText(img1, f'Convexity:{k}', (x, y+30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2) cv2.imshow("Image", img1) cv2.waitKey(0) cv2.destroyAllWindows()
我们将在本程序的输入文件中使用以下图像。

输出
执行后,它将在控制台上生成以下输出:
Number of contours: 1 Convexity: False
并且我们会看到这个窗口,显示输出:

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP