opencv判断轮廓是圆形还是正方形
时间: 2023-06-09 17:08:17 浏览: 282
OpenCV检测正方形、矩形源代码
3星 · 编辑精心推荐
要判断轮廓是圆形还是正方形,可以用OpenCV中的轮廓近似函数approxPolyDP()来对轮廓进行近似,然后根据近似得到的点数来判断形状。如果点数为4,则为正方形;如果点数为多个,则为圆形。代码示例:
```python
import cv2
import numpy as np
img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
if len(approx)==4:
cv2.drawContours(img,[cnt],0,(0,255,0),3)
cv2.putText(img,'Square',(cnt[0][0][0],cnt[0][0][1]), \
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
else:
cv2.drawContours(img,[cnt],0,(0,0,255),3)
cv2.putText(img,'Circle',(cnt[0][0][0],cnt[0][0][1]), \
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文