将输入图像(距离图)和预测图像(RGB)加载到 numpy 数组中。
import cv2
import numpy as np
input_img = cv2.imread('input.png', cv2.IMREAD_GRAYSCALE)
predicted_img = cv2.imread('predicted.png')
对输入图像应用阈值以创建二进制掩码。
_, input_mask = cv2.threshold(input_img, 0, 255, cv2.THRESH_BINARY)
在二进制掩码中找到轮廓。
contours, _ = cv2.findContours(input_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
迭代轮廓并计算预测图像中每个核的拓扑结构。
nuclei_topology = []
for contour in contours:
# Get the bounding box of the contour
x, y, w, h = cv2.boundingRect(contour)
# Create a mask for the current nucleus by cropping the predicted image
nucleus_mask = np.zeros(predicted_img.shape[:2], dtype=np.uint8)
nucleus_mask[y:y+h, x:x+w] = 255
nucleus_mask = cv2.bitwise_and(predicted_img, predicted_img, mask=nucleus_mask)
# Calculate the topology of the nucleus by counting the number of connected components in the mask
_, labels, stats, centroids = cv2.connectedComponentsWithStats(nucleus_mask)
topology = {'nucleus': contour, 'components': stats[1:], 'centroids': centroids[1:]}
nuclei_topology.append(topology)
nuclei_topology
是字典列表,其中每个字典包含输入图像中核的轮廓和预测图像中相应核的拓扑信息。拓扑信息表示为连接组件及其质心的列表。
这只是根据输入轮廓计算核拓扑的一种可能方法。根据输入和输出图像的特性,您可能需要调整阈值方法、轮廓检测算法或拓扑计算方法以获得最佳结果。