该案例主要涉及到不同形状的图形。根据获得轮廓,计算边数。来判断属于什么形状,并将之输出在图片上。具体代码和结果如下:
import cv2
from urllib3 import connection_from_url
img = cv2.imread("pyopencv_again/shape.jpg")
imgconts = img.copy()
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(img,150,200)
conts,_ = cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for cont in conts:
#print(cont)
cv2.drawContours(imgconts,cont,-1,(255,0,0),2)
area = cv2.contourArea(cont)
if area >500:
#计算周长作为精度参数
peri = cv2.arcLength(cont,True)
#多边形逼近轮廓 获得边
vertices = cv2.approxPolyDP(cont,peri*0.02,True)
#统计每个形状的边数
contsnum = len(vertices)
#最大外接矩形 获取(x,y)宽和高
x,y,w,h = cv2.boundingRect(vertices)
if contsnum ==3:
cv2.putText(imgconts,'3',(x,y-5),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),1)
cv2.rectangle(imgconts,(x,y),(x+w,y+h),(0,255,0),2)
if contsnum ==4:
cv2.putText(imgconts,'4',(x,y-5),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),1)
cv2.rectangle(imgconts,(x,y),(x+w,y+h),(124,25,110),2)
if contsnum == 5:
cv2.putText(imgconts,'5',(x,y-5),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),1)
cv2.rectangle(imgconts,(x,y),(x+w,y+h),(1,115,110),2)
if contsnum >= 6:
cv2.putText(imgconts,'circle',(x,y-5),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),1)
cv2.rectangle(imgconts,(x,y),(x+w,y+h),(101,15,10),2)
#cv2.imshow('img',img)
cv2.imshow('imgcont',imgconts)
cv2.waitKey()