import cv2
import numpy as np
img = cv2.imread("../chapter3/hammer.jpg", cv2.IMREAD_UNCHANGED)
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY), 127, 255, cv2.THRESH_BINARY)
contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
for c in contours:
#绘制矩形框
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
rect = cv2.minAreaRect(c)#绘制最小矩形框
box = cv2.boxPoints(rect) #找矩形的四个顶点
box = np.int0(box)
cv2.drawContours(img, [box], 0, (0, 0, 255), 3)
#最小闭圆
(x, y), radius = cv2.minEnclosingCircle(c)
x, y, radius = [int(x) for i in [x, y, radius]]
img = cv2.circle(img, (x, y), radius, (0, 255, 0), 2)
cv2.imshow("contours", cv2.resize(img, dsize=(300, 300)))
cv2.waitKey()
opencv绘制矩形,最小矩形,最小闭圆的轮廓
最新推荐文章于 2024-07-04 06:00:00 发布