如何在 OpenCV Python 中检查图像轮廓是否凸?
opencvpythonserver side programmingprogramming
函数 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
我们得到这个窗口,显示输出 -