这个函数很简单,img是一个二值图,也就是它的参数;
返回四个值,分别是x,y,w,h;
x,y是矩阵左上点的坐标,w,h是矩阵的宽和高
然后利用cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2),画出矩形
参数解释
第一个参数:img是原图
第二个参数:(x,y)是矩阵的左上点坐标
第三个参数:(x+w,y+h)是矩阵的右下点坐标
第四个参数:(0,255,0)是画线对应的rgb颜色
第五个参数:2是所画的线的宽度
img = cv2.imread('tim.jpg')[:300, :300]
img2 = cv2.pyrDown(img, cv2.IMREAD_UNCHANGED)
ret, thresh = cv2.threshold(cv2.cvtColor(img2.copy(), cv2.COLOR_BGR2GRAY), 127, 255, cv2.THRESH_BINARY)
contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(np.array(contours).shape)
# print(contours)
for c in contours:
# 边界框
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(img2, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 最小外接矩阵
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img2, [box], -1, (0, 0, 255), 2)
# 最小外接闭圆
(x, y), radius = cv2.minEnclosingCircle(c)
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img2, center, radius, (0, 255, 0), 2)
cv2.drawContours(img, contours, -1, (255, 0, 0), 1)
a(img2)