opencv——利用轮廓信息画斜矩形、外接圆、拟合直线等

本文通过使用Python的OpenCV库,详细介绍了如何从图像中提取轮廓,并计算和绘制轮廓的各种特征,包括旋转矩阵、直边界矩阵、外接圆、外接椭圆及拟合曲线等。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 20:14:10 2017

@author: fs
"""

import cv2
import numpy as np
img = cv2.imread('lunkuo1.png')

ret,thresh = cv2.threshold(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY),127,255,0)
_,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)#得到轮廓信息
cnt = contours[0]#取第一条轮廓

#%% 计算轮廓的旋转矩阵
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)

#计算轮廓的直边界矩阵
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)


#计算轮廓外接圆
(rx,ry),radius = cv2.minEnclosingCircle(cnt)
center = (int(rx),int(ry))
radius = int(radius)
cv2.circle(img,center,radius,(255,0,0),2)

#计算轮廓外接椭圆
ellipse = cv2.fitEllipse(cnt)
cv2.ellipse(img,ellipse,(125,125,255),5)

#轮廓拟合曲线
rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)
cv2.imshow('lunkuo1',img)

cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值