如何正确计算图像中每个单元的相邻单元数?

问题描述 投票:0回答:1

[请在二进制图像中计算六边形单元的百分比(例如,具有6个相邻单元的单元数/单元总数),并生成彩色编码图像,如下所示。

我已经尝试过下面的python代码,但没有得到正确的输出。随附了二进制图像及其输出的示例。

import sys
import json
import cv2
import os
import scipy.io
import numpy as np
from scipy.ndimage import measurements, morphology
from skimage import measure
import time


def cells_measurements(path, orig_image, color="yellow", size=3, pixel_sz=0.00104167):
    size = int(size)
    im = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    _, im = cv2.threshold(im, 127, 255, cv2.THRESH_BINARY)
    labeled_image, num_of_cells = measurements.label(255 - im)
    props = measure.regionprops(labeled_image)
     number_of_cells = len(props)

    colored_image = np.pad(cv2.cvtColor(~im, cv2.COLOR_GRAY2BGR), ((1, 1), (1, 1), (0, 0,)), 
     constant',constant_values=0)

   colors = [[0, 0, 128], [0, 0, 255], [0, 128, 255], [0, 255, 255], [128, 255, 128], [255, 255, 0], 
   [255, 128, 0],[255, 0, 0]]

   count_hex = 0
   labels = np.unique(labeled_image)
   for l in labels[1:]:
       i_temp = (labeled_image == l).astype(float) * 255
       i_temp = cv2.dilate(i_temp, np.ones((3, 3)), iterations=2) - i_temp
       i_temp2 = np.copy(labeled_image)
       i_temp2[i_temp == 0.] = 0
       adjacent = len(np.unique(i_temp2)) - 1
       if adjacent == 6:
          count_hex += 1
       cv2.floodFill(colored_image, None, (int(cell_center_all[l - 1][1]), int(cell_center_all[l - 1] 
        [0])), colors[min(adjacent, 7)])

       hexagonal_cells = (count_hex / num_of_cells) * 100

       colored_image = np.pad(colored_image, ((0, 0), (0, 75), (0, 0)), 'constant', 
       constant_values=255)
       for i in range(8):
           step = colored_image.shape[0] // 8
           colored_image[i * step:+(i + 1) * step, -60:-35] = colors[7 - i]
           colored_image[i * step, -60:-35] = 0
           colored_image[(i + 1) * step, -60:-35] = 0
           colored_image[i * step:(i + 1) * step, -60] = 0
           colored_image[i * step:(i + 1) * step, -35] = 0
           cv2.putText(colored_image, str(7 - i), (colored_image.shape[1] - 30, 5 + i * step + step 
            // 2), cv2.FONT_HERSHEY_DUPLEX, 0.5, 0)

      color_path = 'Labeled Images/' + fn + "_color.png"
      cv2.imwrite(color_path, colored_image)

The binary image

您可以看到二进制图像的边缘有些模糊。如何提高他们的知名度?

Colored coded image

python python-3.x image image-processing image-segmentation
1个回答
0
投票

一种方法可能是使用分水岭算法进行分割。

在这里阅读:

© www.soinside.com 2019 - 2024. All rights reserved.