python-opencv獲取二值圖像輪廓及中心點(diǎn)坐標(biāo)代碼:
groundtruth = cv2.imread(groundtruth_path)[:, :, 0] h2, w1 = groundtruth.shape contours, cnt = cv2.findContours(groundtruth.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if len(contours) != 1:#輪廓總數(shù) continue M = cv2.moments(contours[0]) # 計(jì)算第一條輪廓的各階矩,字典形式 center_x = int(M["m10"] / M["m00"]) center_y = int(M["m01"] / M["m00"]) image = np.zeros([h2, w1], dtype=groundtruth.dtype) cv2.drawContours(image, contours, 0, 255, -1)#繪制輪廓,填充 cv2.circle(image, (center_x, center_y), 7, 128, -1)#繪制中心點(diǎn) cv2.imwrite("1.png", image)