为图像中的不同生物细胞分配不同的颜色

Assign different colors to different biological cells in an image

我需要为图像中的不同生物细胞分配不同的颜色。

更具体地说,图像只是黑白的(因此只有 0 和 255 的矩阵)。单元格的内容(不包括边界)用白色表示,而单元格边界用黑色表示。每个单元格都被一些单元格边界或图像边缘包围。我希望为不同的单元格分配不同的颜色,这样我可以通过查看其条目的值立即知道我当前所在的单元格。


编辑:是生物细胞。我在网上找到了类似的东西:

来源:http://brainiac2.mit.edu/isbi_challenge/

想到一个简单的方法:

  1. 阈值图像以将其二值化,因为您提供的图像不仅仅包含 0 和 255。

  2. 找到所有的轮廓并将它们组织成两级层次结构。这可以通过使用标志 RETR_CCOMP:

    调用 cv2.threshold 来完成

    At the top level, there are external boundaries of the components. At the second level, there are boundaries of the holes. If there is another contour inside a hole of a connected component, it is still put at the top level.

    N.B.: "Components"是图像的白色部分,"holes"是黑色部分。

  3. 遍历轮廓。对于组件的每个轮廓(由于此类轮廓位于层次结构的顶层,因此它们没有父轮廓)绘制填充随机颜色的轮廓多边形。


示例代码:

import cv2
import numpy as np

img = cv2.imread('cells.png', cv2.IMREAD_GRAYSCALE)
thresh = cv2.threshold(img, thresh=128, maxval=255, type=cv2.THRESH_BINARY)[1]
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

output = cv2.cvtColor(thresh, cv2.COLOR_GRAY2BGR)
for i, contour in enumerate(contours):
    if hierarchy[0][i][3] == -1:
        colour = cv2.randu(np.zeros(3, np.uint8), 0, 256)
        cv2.drawContours(output, contours, i, colour.tolist(), -1)

cv2.imwrite('cells_colour.png', output)

结果: