✨博客主页:米开朗琪罗~
✨博主爱好:羽毛球
✨年轻人要:Living for the moment(活在当下)!
推荐专栏:【图像处理】【千锤百炼Python】【深度学习】【排序算法】
函数:rect = cv2.minAreaRect(contours)
参数介绍:
函数:points = cv2.boxPoints(rect)
参数介绍:
import cv2
import numpy as np
original = cv2.imread(r'C:\Users\Lenovo\Desktop\contour.jpg')
# 查找物体轮廓
def findcontour(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 图像灰度化
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 图像二值化
image, contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 查找物体轮廓
return image, contours, hierarchy
image, contours, hierarchy = findcontour(original)
nums = len(contours)
for i in range(nums):
temp = np.zeros(original.shape, np.uint8)
# 绘制最小外接矩形框
rect = cv2.minAreaRect(contours[i]) # rect返回矩形的特征信息,其结构为【最小外接矩形的中心(x,y),(宽度,高度),旋转角度】
points = cv2.boxPoints(rect) # 得到最小外接矩形的四个点坐标
points = np.int0(points) # 坐标值取整
image = cv2.drawContours(original, [points], 0, (0, 0, 255), 2) # 直接在原图上绘制矩形框
cv2.imshow("result", image)
cv2.waitKey()
函数:(x,y), radius = cv2.minEnclosingCircle(contours)
参数介绍:
for i in range(nums):
(x, y), radius = cv2.minEnclosingCircle(contours[i])
center = (int(x), int(y))
radius = int(radius)
image = cv2.circle(original, center, radius, (255, 0, 0), 2)
cv2.imwrite(r'C:\Users\Lenovo\Desktop\result.jpg', image)
cv2.imshow("result", image)
cv2.waitKey()