|
|
应用一下代码可以找到灰度图片的cnts:
# 模糊处理
blurred = cv.GaussianBlur(gray, (19, 19), 0)
# 使用otsu查找最佳阈值ret
ret, thresh = cv.threshold(blurred, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
# threshold 二值化处理
thresh = cv.threshold(blurred, ret, 255, cv.THRESH_BINARY_INV)[1]
# find contours in the thresholded image
cnts = cv.findContours(thresh.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
然后在for循环里对cnts里的每一个cnt进行遍历操作即可:
for cnt in cnts:
# compute the center of the contour
M = cv.moments(cnt)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# draw the contour and center of the shape on the image
cv.drawContours(img, [cnt], -1, (0, 255, 0), 2)
#画中心点
cv.circle(img, (cX, cY), 7, (0, 0, 0), -1)
#画轮廓
cv.putText(img, "center", (cX - 20, cY - 20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
rect = cv.minAreaRect(cnt)
print("中心坐标:", rect[0])
print("宽度:", rect[1][0])
print("长度:", rect[1][1])
print("旋转角度:", rect[2])
box = cv.boxPoints(rect) # cv.boxPoints(rect) for OpenCV 3.x 获取最小外接矩形的4个顶点
box = np.int0(box)
print("四个顶点坐标为;", box)
draw_img = cv.drawContours(img, [box], -1, (0, 0, 255), 3)