opencv-python最⼩外接矩形
opencv—python 最⼩外接矩形
(编程⼩⽩,如有问题还请各位⼤佬多指教)
所⽤函数:
cv2.threshold() —— 阈值处理
cv2.findContours() —— 轮廓检测
cv2.boundingRect() —— 最⼤外接矩阵
cv2.minAreaRect —— 到最⼩外接矩形(矩形具有⼀定的⾓度)
cv2.boxPoints —— 外接矩形的坐标位置
cv2.drawContours(image, [box], 0, (0, 0, 255), 3) —— 根据点画出矩形
import cv2
import numpy as np
rectangle函数opencvimage = cv2.imread('new.jpg')
img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img,230,255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# 到边界坐标
x, y, w, h = cv2.boundingRect(c)# 计算点集最外⾯的矩形边界
# ⾯积最⼩的矩形
rect = cv2.minAreaRect(c)
# 得到最⼩矩形的坐标
box = cv2.boxPoints(rect)
# 标准化坐标到整数
box = np.int0(box)
# 画出边界
cv2.drawContours(image,[box],0,(0,0,255),3)
# 计算最⼩封闭圆的中⼼和半径
(x, y), radius = cv2.minEnclosingCircle(c)
# 换成整数integer
center =(int(x),int(y))
radius =int(radius)
# 画圆
cv2.circle(image, center, radius,(0,255,0),2)
cv2.drawContours(image, contours,-1,(255,0,0),1)
cv2.imshow("img", image)
cv2.imwrite("img_1.jpg", image)
cv2.waitKey(0)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。