基于opencv的常用轮廓拟合方法总结

import cv2
import numpy as np
img = cv2.imread("image.jpg") #读取图像
r1 = cv2.GaussianBlur(img,(7,7),0,0) # 高斯滤波
gray = cv2.cvtColor(r1,cv2.COLOR_BGR2GRAY) #灰度处理
t,r = cv2.threshold(gray,30,255,cv2.THRESH_BINARY) #阈值分割
kernel = np.ones((5,5),np.uint8) #结构元,核越大腐蚀越严重
erosion = cv2.erode(r,kernel,iterations=10) #腐蚀函数,iteration迭代次数
dilation = cv2.dilate(erosion,kernel,iterations=10) # 膨胀
contours, hierarchy =cv2.findContours(dilation,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) #

# 外接矩形
x,y,w,h = cv2.boundingRect(contours[0])
brcnt = np.array([[[x,y]],[[x+w,y]],[[x+w,y+h]],[[x,y+h]]])
cv2.drawContours(img,[brcnt],-1,(255,255),2)

# 外接最小矩形
rect = cv2.minAreaRect(contours[0])
point = cv2.boxPoints(rect)
point = np.int0(point)
cv2.drawContours(img,[point],-1,(255,255),2)

# 外接圆
(q, p), radius = cv2.minEnclosingCircle(contours[0])
center = (int(q), int(p))
radius = int (radius)
cv2.circle(img, center, radius, (255, 255), 2)

# 外接最优拟合椭圆
ellipse = cv2.fitEllipse(contours[0])
cv2.ellipse(img, ellipse, (255, 255),2)

# 外接三角形
area, trl = cv2.minEnclosingTriangle(contours[0])
for i in range(0, 3):
    p0 = trl[i, 0] # 点(i,0)
    p1 = [int(j) for j in p0] # 由float转为int
    p3 = trl[(i + 1) % 3, 0]  # 点
    p4 = [int(j) for j in p3] # 转为int
    cv2.line(img,tuple(p1),tuple(p4),(255,255),2)


#  显示矩形边界
cv2.imshow("result",img)
cv2.waitKey()
cv2.destroyAllWindows()

结果如下:
(1)原图
基于opencv的常用轮廓拟合方法总结_第1张图片
(2)各方法结果图(截取了结果的部分图,所以和原图尺寸不一样)
基于opencv的常用轮廓拟合方法总结_第2张图片

你可能感兴趣的:(python,opencv,opencv,python)