python opencv 基础形状查找 实例
2022/2/28 22:23:24
本文主要是介绍python opencv 基础形状查找 实例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
test.png
import cv2 import numpy as np #定义形状检测函数 def ShapeDetection(img): contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) #寻找轮廓点 for obj in contours: area = cv2.contourArea(obj) #计算轮廓内区域的面积 cv2.drawContours(imgContour, obj, -1, (255, 0, 0), 4) #绘制轮廓线 perimeter = cv2.arcLength(obj,True) #计算轮廓周长 approx = cv2.approxPolyDP(obj,0.02*perimeter,True) #获取轮廓角点坐标 CornerNum = len(approx) #轮廓角点的数量 x, y, w, h = cv2.boundingRect(approx) #获取坐标值和宽度、高度 #轮廓对象分类 if CornerNum ==3: objType ="triangle" elif CornerNum == 4: if w==h: objType= "Square" else:objType="Rectangle" elif CornerNum>4: objType= "Circle" else:objType="N" cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,0,255),2) #绘制边界框 cv2.putText(imgContour,objType,(x+(w//2),y+(h//2)),cv2.FONT_HERSHEY_COMPLEX,0.6,(0,0,0),1) #绘制文字 path = "./test.png" img = cv2.imread(path) imgContour = img #imgGray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) #转灰度图 #imgBlur = cv2.GaussianBlur(imgGray,(5,5),1) #高斯模糊 imgCanny = cv2.Canny(img,60,60) #Canny算子边缘检测 ShapeDetection(imgCanny) #形状检测 cv2.imshow("Original img", img) #cv2.imshow("imgGray", imgGray) #cv2.imshow("imgBlur", imgBlur) cv2.imshow("imgCanny", imgCanny) cv2.imshow("shape Detection", imgContour) cv2.waitKey(0)
运行结果:
这篇关于python opencv 基础形状查找 实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门
- 2024-11-14Python编程入门指南
- 2024-11-13Python基础教程
- 2024-11-12Python编程基础指南
- 2024-11-12Python基础编程教程
- 2024-11-08Python编程基础与实践示例
- 2024-11-07Python编程基础指南
- 2024-11-06Python编程基础入门指南
- 2024-11-06怎么使用python 计算两个GPS的距离功能-icode9专业技术文章分享