示例#1
0
    def test_h_maxima(self):
        "h-maxima for various data types"

        data = np.array([[10,  11,  13,  14,  14,  15,  14,  14,  13,  11],
                         [11,  13,  15,  16,  16,  16,  16,  16,  15,  13],
                         [13,  15,  40,  40,  18,  18,  18,  60,  60,  15],
                         [14,  16,  40,  40,  19,  19,  19,  60,  60,  16],
                         [14,  16,  18,  19,  19,  19,  19,  19,  18,  16],
                         [15,  16,  18,  19,  19,  20,  19,  19,  18,  16],
                         [14,  16,  18,  19,  19,  19,  19,  19,  18,  16],
                         [14,  16,  80,  80,  19,  19,  19, 100, 100,  16],
                         [13,  15,  80,  80,  18,  18,  18, 100, 100,  15],
                         [11,  13,  15,  16,  16,  16,  16,  16,  15,  13]],
                        dtype=np.uint8)

        expected_result = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
                                   dtype=np.uint8)
        for dtype in [np.uint8, np.uint64, np.int8, np.int64]:
            data = data.astype(dtype)
            out = extrema.h_maxima(data, 40)

            error = diff(expected_result, out)
            assert error < eps
示例#2
0
def predict(model, dataloader=None, image=None):
    model.eval()
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    if image is not None:
        image = image[0].to(device=device)[None, :, :, :]
        start_time = time.time()
        with torch.no_grad():
            outputs = model(image)
        out = outputs[0, 0, :, :].numpy()

        h = 0.3
        h_maxima = extrema.h_maxima(out, h)
        coordinates_h = peak_local_max(h_maxima, indices=True)
        elapsed_time = time.time() - start_time
        pred_x = coordinates_h[:, 1]
        pred_y = coordinates_h[:, 0]
        image = image[0, 0, :, :].detach().cpu().numpy()
        return image, pred_x, pred_y

    for i, (inputs, name) in enumerate(dataloader):
        name = name[0]
        start_time = time.time()
        with torch.no_grad():
            inputs = inputs[0].to(device=device)[None, :, :, :]
            outputs = model(inputs)
        out = outputs[0, 0, :, :].numpy()

        h = 0.3
        h_maxima = extrema.h_maxima(out, h)
        coordinates_h = peak_local_max(h_maxima, indices=True)
        elapsed_time = time.time() - start_time

        fig = plt.figure(dpi=300)
        ax = fig.add_subplot(1, 1, 1)
        ax.imshow(inputs[0, 0, :, :].detach().cpu().numpy(), cmap="gray")
        ax.plot(coordinates_h[:, 1], coordinates_h[:, 0], 'r+', markersize=10)
        print(f"{name}, time: {elapsed_time}")
        plt.show()
        break
示例#3
0
def h_max_transform(img, h):

    # if h <= 0:
    #     h = 1
    # else:
    #     h = 1/h

    print("Foci threshold is " + str(h))
    h_maxima = extrema.h_maxima(img, h)
    label_h_maxima = label(h_maxima)

    label_h_maxima[label_h_maxima > 0] = 255

    return label_h_maxima
示例#4
0
    def test_extrema_float(self):
        "specific tests for float type"
        data = np.array(
            [[0.10, 0.11, 0.13, 0.14, 0.14, 0.15, 0.14, 0.14, 0.13, 0.11],
             [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.15, 0.13],
             [0.13, 0.15, 0.40, 0.40, 0.18, 0.18, 0.18, 0.60, 0.60, 0.15],
             [0.14, 0.16, 0.40, 0.40, 0.19, 0.19, 0.19, 0.60, 0.60, 0.16],
             [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.18, 0.16],
             [0.15, 0.182, 0.18, 0.19, 0.204, 0.20, 0.19, 0.19, 0.18, 0.16],
             [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19, 0.19, 0.18, 0.16],
             [0.14, 0.16, 0.80, 0.80, 0.19, 0.19, 0.19, 1.0, 1.0, 0.16],
             [0.13, 0.15, 0.80, 0.80, 0.18, 0.18, 0.18, 1.0, 1.0, 0.15],
             [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16, 0.16, 0.15, 0.13]],
            dtype=np.float32)
        inverted_data = 1.0 - data

        expected_result = np.array(
            [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
             [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
            dtype=np.uint8)

        # test for local maxima with automatic step calculation
        out = extrema.local_maxima(data)
        error = diff(expected_result, out)
        assert error < eps

        # test for local minima with automatic step calculation
        out = extrema.local_minima(inverted_data)
        error = diff(expected_result, out)
        assert error < eps

        out = extrema.h_maxima(data, 0.003)
        expected_result = np.array(
            [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
             [0, 0, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
            dtype=np.uint8)

        error = diff(expected_result, out)
        assert error < eps

        out = extrema.h_minima(inverted_data, 0.003)
        error = diff(expected_result, out)
        assert error < eps
示例#5
0
    def getExtrema(self):
        Extrema = np.array([0, 0, 0])

        img = self.ch1
        image_gray = img
        image_rgb = img
        im = self.runHistogramAbs(img)
        # im = ndimage.gaussian_filter(im, sigma=0.7)
        # im = exposure.rescale_intensity(im)
        im = ndimage.gaussian_filter(im, sigma=1)
        im = exposure.rescale_intensity(im)
        h = 0.2
        h_maxima = extrema.h_maxima(im, h)
        label_h_maxima = label(h_maxima)
        Extrema[0] = np.count_nonzero(label_h_maxima)

        #check if the extrema is right next to the edge
        if Extrema[0] == 1:
            indices = np.nonzero(h_maxima)
            distance = im.shape[1] - indices[1]
            Extrema[2] = distance[0]

        img = self.ch6
        image_gray = img
        image_rgb = img
        im = self.runHistogramAbs(img)
        # im = ndimage.gaussian_filter(im, sigma=0.7)
        im = ndimage.gaussian_filter(im, sigma=1)
        im = exposure.rescale_intensity(im)
        h = 0.2
        h_maxima = extrema.h_maxima(im, h)
        label_h_maxima = label(h_maxima)
        Extrema[1] = np.count_nonzero(label_h_maxima)
        params = self.getParams()
        Extrema = np.append(Extrema, params)
        return Extrema
示例#6
0
def segment_watershed(pixels: np.array, extreme_val: int, bg_val: int):
    """
    Returns an np.array that is the segmented version of the input

        Finds local maxima using extreme_val as the minimal height for the maximum,
        Then uses the local maxima and background pixels (pixels that are
        smaller than bg_val) to execute a watershed segmentation
    """
    maxima = extrema.h_maxima(pixels, extreme_val)
    elevation_map = sobel(pixels)
    markers = np.zeros_like(pixels)
    markers[pixels < bg_val] = 1
    markers[maxima == 1] = 2

    return segmentation.watershed(elevation_map, markers)
示例#7
0
def h_max_transform(img, h):

    if h <= 0:
        h = 1
    else:
        h = 1 / h
    print("Foci threshold is " + str(h))
    h_maxima = extrema.h_maxima(img, h)
    label_h_maxima = label(h_maxima)
    overlay_h = color.label2rgb(label_h_maxima,
                                img,
                                alpha=0.7,
                                bg_label=0,
                                bg_color=None,
                                colors=[(1, 0, 0)])
    return overlay_h
示例#8
0
def ExtractCandidates(im_norm, h, radius, nbit):
    """extract signal candidates applying h_maxima transform 
    INPUTS:
        im_norm=normalised image,
        h=h_maxima threshold,
        radius=structuring element radius,
        nbit= encoding"""

    #top_hat filtering
    se = ball(radius)
    im = white_tophat(im_norm, se)
    connectivity = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]],
                             [[0, 1, 0], [1, 1, 1], [0, 1, 0]],
                             [[0, 0, 0], [0, 1, 0], [0, 0, 0]]])  #3D corss

    #filtering local maxima
    h_maxima = extrema.h_maxima(im, h, selem=connectivity)
    label_h_max = label(h_maxima, neighbors=4)
    labels = pd.DataFrame(
        data={'labels': np.sort(label_h_max[np.where(label_h_max != 0)])})
    dup = labels.index[labels.duplicated() == True].tolist(
    )  #find duplicates labels (=connected components)

    #splitting connected regions to get only one local maxima
    max_mask = np.zeros(im.shape)
    max_mask[label_h_max != 0] = np.iinfo(nbit).max

    for i in range(len(dup)):
        z, r, c = np.where(label_h_max == labels.loc[
            dup[i], 'labels'])  #find coord of points having the same label
        meanpoint_x = np.mean(c)
        meanpoint_y = np.mean(r)
        meanpoint_z = np.mean(z)
        dist = [
            distance.euclidean([meanpoint_z, meanpoint_y, meanpoint_x],
                               [z[j], r[j], c[j]]) for j in range(len(r))
        ]
        ind = dist.index(min(dist))
        z, r, c = np.delete(z, ind), np.delete(r, ind), np.delete(
            c, ind)  #delete values at ind position.
        max_mask[z, r, c] = 0  #set to 0 points != medoid coordinates

##    overlay_h=color.label2rgb(label_h_max, im, alpha=1, bg_label=0, bg_color=None, colors=[(0,1,0)])
##    plt.figure()
##    plt.imshow(overlay_h,interpolation='none')

    return max_mask
示例#9
0
    def test_h_maxima_float_image(self):
        """specific tests for h-maxima float image type"""
        w = 10
        x, y = np.mgrid[0:w, 0:w]
        data = 20 - 0.2 * ((x - w / 2) ** 2 + (y - w / 2) ** 2)
        data[2:4, 2:4] = 40
        data[2:4, 7:9] = 60
        data[7:9, 2:4] = 80
        data[7:9, 7:9] = 100
        data = data.astype(np.float32)

        expected_result = np.zeros_like(data)
        expected_result[(data > 19.9)] = 1.0

        for h in [1.0e-12, 1.0e-6, 1.0e-3, 1.0e-2, 1.0e-1, 0.1]:
            out = extrema.h_maxima(data, h)
            error = diff(expected_result, out)
            assert error < eps
示例#10
0
    def test_extrema_float(self):
        """specific tests for float type"""
        data = np.array([[0.10, 0.11, 0.13, 0.14, 0.14, 0.15, 0.14,
                          0.14, 0.13, 0.11],
                         [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16,
                          0.16, 0.15, 0.13],
                         [0.13, 0.15, 0.40, 0.40, 0.18, 0.18, 0.18,
                          0.60, 0.60, 0.15],
                         [0.14, 0.16, 0.40, 0.40, 0.19, 0.19, 0.19,
                          0.60, 0.60, 0.16],
                         [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19,
                          0.19, 0.18, 0.16],
                         [0.15, 0.182, 0.18, 0.19, 0.204, 0.20, 0.19,
                          0.19, 0.18, 0.16],
                         [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19,
                          0.19, 0.18, 0.16],
                         [0.14, 0.16, 0.80, 0.80, 0.19, 0.19, 0.19,
                          1.0, 1.0, 0.16],
                         [0.13, 0.15, 0.80, 0.80, 0.18, 0.18, 0.18,
                          1.0, 1.0, 0.15],
                         [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16,
                          0.16, 0.15, 0.13]],
                        dtype=np.float32)
        inverted_data = 1.0 - data

        out = extrema.h_maxima(data, 0.003)
        expected_result = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
                                   dtype=np.uint8)

        error = diff(expected_result, out)
        assert error < eps

        out = extrema.h_minima(inverted_data, 0.003)
        error = diff(expected_result, out)
        assert error < eps
示例#11
0
    def test_extrema_float(self):
        """specific tests for float type"""
        data = np.array([[0.10, 0.11, 0.13, 0.14, 0.14, 0.15, 0.14,
                          0.14, 0.13, 0.11],
                         [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16,
                          0.16, 0.15, 0.13],
                         [0.13, 0.15, 0.40, 0.40, 0.18, 0.18, 0.18,
                          0.60, 0.60, 0.15],
                         [0.14, 0.16, 0.40, 0.40, 0.19, 0.19, 0.19,
                          0.60, 0.60, 0.16],
                         [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19,
                          0.19, 0.18, 0.16],
                         [0.15, 0.182, 0.18, 0.19, 0.204, 0.20, 0.19,
                          0.19, 0.18, 0.16],
                         [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19,
                          0.19, 0.18, 0.16],
                         [0.14, 0.16, 0.80, 0.80, 0.19, 0.19, 0.19,
                          1.0, 1.0, 0.16],
                         [0.13, 0.15, 0.80, 0.80, 0.18, 0.18, 0.18,
                          1.0, 1.0, 0.15],
                         [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16,
                          0.16, 0.15, 0.13]],
                        dtype=np.float32)
        inverted_data = 1.0 - data

        out = extrema.h_maxima(data, 0.003)
        expected_result = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
                                   dtype=np.uint8)

        error = diff(expected_result, out)
        assert error < eps

        out = extrema.h_minima(inverted_data, 0.003)
        error = diff(expected_result, out)
        assert error < eps
示例#12
0
 def accumfindcenters(self,acc, senstivity):
     accumMatrix = np.absolute(acc) # accumulator array
     sigma  = 0.5
     kernel = int(2*np.ceil(2*sigma)+1)
     accumMatrix = cv2.GaussianBlur(accumMatrix , (kernel,kernel),sigmaX=0.5)
     senstivity = 0.93 # default
     Hd = cv2.medianBlur(accumMatrix.astype('float32'),5)
     accumThresh = 1-senstivity
     suppThreshold = np.max(accumThresh-  np.spacing(accumThresh),0)
     Hd = extrema.h_maxima(Hd, suppThreshold)
     bw = (local_maxima(Hd)).astype(int)
     label_img = label(bw, connectivity=bw.ndim)
     s = regionprops(label_img, intensity_image=accumMatrix)
     center = np.empty([len(s),2])
     metric = np.empty([len(s),1])
     for index,i in enumerate(s):
       center[index] = tuple((np.array(s[index].centroid)).astype(int))
       metric[index] = Hd[tuple((np.array(s[index].centroid)).astype(int))]
     return center, metric
示例#13
0
    def showMaxima(self, im):
        fig = plt.figure()
        plt.imshow(im)
        im = self.runHistogramAbs(im)
        im = ndimage.gaussian_filter(im, sigma=1)
        im = exposure.rescale_intensity(im)
        h = 0.2
        h_maxima = extrema.h_maxima(im, h)
        label_h_maxima = label(h_maxima)
        img = skimage.exposure.rescale_intensity(im)
        overlay_h = color.label2rgb(label_h_maxima,
                                    img,
                                    alpha=0.7,
                                    bg_label=0,
                                    bg_color=None)
        plt.imshow(overlay_h)

        plt.show()
        return
示例#14
0
def contour_pm_watershed(contour_pm,
                         sigma=2,
                         h=0,
                         tissue_mask=None,
                         padding_mask=None,
                         min_area=None,
                         max_area=None):
    if tissue_mask is None:
        tissue_mask = np.ones_like(contour_pm)
    padded = None
    if padding_mask is not None and np.any(padding_mask == 0):
        contour_pm, padded = crop_with_padding_mask(contour_pm,
                                                    padding_mask,
                                                    return_mask=True)
        tissue_mask = crop_with_padding_mask(tissue_mask, padding_mask)

    maxima = peak_local_max(extrema.h_maxima(ndi.gaussian_filter(
        np.invert(contour_pm), sigma=sigma),
                                             h=h),
                            indices=False,
                            footprint=np.ones((3, 3)))
    maxima = label(maxima).astype(np.int32)

    # Passing mask into the watershed function will exclude seeds outside
    # of the mask, which gives fewer and more accurate segments
    maxima = watershed(
        contour_pm, maxima, watershed_line=True, mask=tissue_mask) > 0

    if min_area is not None and max_area is not None:
        maxima = label(maxima, connectivity=1).astype(np.int32)
        areas = np.bincount(maxima.ravel())
        size_passed = np.arange(areas.size)[np.logical_and(
            areas > min_area, areas < max_area)]
        maxima *= np.isin(maxima, size_passed)
        np.greater(maxima, 0, out=maxima)

    if padded is None:
        return maxima.astype(np.bool)
    else:
        padded[padded == 1] = maxima.flatten()
        return padded.astype(np.bool)
示例#15
0
    def test_h_maxima_float_h(self):
        """specific tests for h-maxima float h parameter"""
        data = np.array([[0, 0, 0, 0, 0], [0, 3, 3, 3, 0], [0, 3, 4, 3, 0],
                         [0, 3, 3, 3, 0], [0, 0, 0, 0, 0]],
                        dtype=np.uint8)

        h_vals = np.linspace(1.0, 2.0, 100)
        failures = 0

        for h in h_vals:
            if h % 1 != 0:
                msgs = ['possible precision loss converting image']
            else:
                msgs = []

            with expected_warnings(msgs):
                maxima = extrema.h_maxima(data, h)

            if (maxima[2, 2] == 0):
                failures += 1

        assert (failures == 0)
示例#16
0
def make_labels_h5(path_to_h5, gridname, peak_min =4.0, dist_min=0.5, apply_pbc=True, extra_maxi=[]):

    import h5py
    import numpy as np
    from skimage.morphology import extrema
    import scipy.ndimage as ndi
    from skimage.morphology import watershed

    hfile         = h5py.File(path_to_h5,'r')
    dgrid_np      = np.array(hfile[gridname])
    local_maxi    = extrema.h_maxima(dgrid_np, peak_min)
    if len(extra_maxi)>0:
        for e in extra_maxi:
            local_maxi[tuple(e)] = 1
    maxi_markers  = ndi.label(local_maxi)[0] # Identify feature sand label those in the 3D array
    masked_image  = dgrid_np>dist_min # Mask for the watershed
    # distance = ndi.distance_transform_edt(masked_image)
    # dgrid_np[dgrid_np<0]=0
    region_labels = watershed(-dgrid_np, markers=maxi_markers, mask=masked_image.astype(np.int))
    if apply_pbc:
        rlpbc         = apply_pbc3(region_labels, local_maxi)
        return rlpbc, local_maxi, dgrid_np[np.where(local_maxi)]
    else:
        return region_labels, local_maxi, dgrid_np[np.where(local_maxi)]
示例#17
0
def label_watershed(obj: np.array, maxima_threshold):
    """
    Separate touching objects based on distance map (similar to imageJ watershed)

    :param obj: np.array, 0-and-1
    :param maxima_threshold: threshold for identify maxima
    :return: seg: np.array, grey scale with different objects labeled with different numbers
    """
    _, dis = medial_axis(obj, return_distance=True)
    maxima = extrema.h_maxima(dis, maxima_threshold)
    # maxima_threshold for Jess data = 1
    # maxima_threshold for Jose data = 10
    maxima_mask = binary_dilation(maxima)
    for i in range(6):
        maxima_mask = binary_dilation(maxima_mask)

    label_maxima = label(maxima_mask, connectivity=2)
    markers = label_maxima.copy()
    markers[obj == 0] = np.amax(label_maxima) + 1
    elevation_map = sobel(obj)
    label_obj = segmentation.watershed(elevation_map, markers)
    label_obj[label_obj == np.amax(label_maxima) + 1] = 0

    return label_obj
示例#18
0
    def test_extrema_float(self):
        "specific tests for float type"
        data = np.array([[0.10, 0.11, 0.13, 0.14, 0.14, 0.15, 0.14,
                          0.14, 0.13, 0.11],
                         [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16,
                          0.16, 0.15, 0.13],
                         [0.13, 0.15, 0.40, 0.40, 0.18, 0.18, 0.18,
                          0.60, 0.60, 0.15],
                         [0.14, 0.16, 0.40, 0.40, 0.19, 0.19, 0.19,
                          0.60, 0.60, 0.16],
                         [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19,
                          0.19, 0.18, 0.16],
                         [0.15, 0.182, 0.18, 0.19, 0.204, 0.20, 0.19,
                          0.19, 0.18, 0.16],
                         [0.14, 0.16, 0.18, 0.19, 0.19, 0.19, 0.19,
                          0.19, 0.18, 0.16],
                         [0.14, 0.16, 0.80, 0.80, 0.19, 0.19, 0.19,
                          1.0,  1.0, 0.16],
                         [0.13, 0.15, 0.80, 0.80, 0.18, 0.18, 0.18,
                          1.0, 1.0, 0.15],
                         [0.11, 0.13, 0.15, 0.16, 0.16, 0.16, 0.16,
                          0.16, 0.15, 0.13]],
                        dtype=np.float32)
        inverted_data = 1.0 - data

        expected_result = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
                                   dtype=np.uint8)

        # test for local maxima with automatic step calculation
        out = extrema.local_maxima(data)
        error = diff(expected_result, out)
        assert error < eps

        # test for local minima with automatic step calculation
        out = extrema.local_minima(inverted_data)
        error = diff(expected_result, out)
        assert error < eps

        out = extrema.h_maxima(data, 0.003)
        expected_result = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 0],
                                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
                                   dtype=np.uint8)

        error = diff(expected_result, out)
        assert error < eps

        out = extrema.h_minima(inverted_data, 0.003)
        error = diff(expected_result, out)
        assert error < eps
示例#19
0
def S3NucleiSegmentationWatershed(nucleiPM, nucleiImage, logSigma, TMAmask,
                                  nucleiFilter, nucleiRegion):
    nucleiContours = nucleiPM[:, :, 1]
    nucleiCenters = nucleiPM[:, :, 0]

    mask = resize(TMAmask, (nucleiImage.shape[0], nucleiImage.shape[1]),
                  order=0) > 0

    if nucleiRegion == 'localThreshold':
        Imax = peak_local_max(extrema.h_maxima(255 - nucleiContours,
                                               logSigma[0]),
                              indices=False)
        Imax = label(Imax).astype(np.int32)
        foregroundMask = watershed(nucleiContours, Imax, watershed_line=True)
        P = regionprops(
            foregroundMask,
            np.amax(nucleiCenters) - nucleiCenters - nucleiContours)
        prop_keys = ['mean_intensity', 'label']

        def props_of_keys(prop, keys):
            return [prop[k] for k in keys]

        mean_ints, labels = np.array(
            Parallel(n_jobs=6)(delayed(props_of_keys)(prop, prop_keys)
                               for prop in P)).T
        del P
        passed = np.less(mean_ints, 50)
        foregroundMask *= np.isin(foregroundMask, labels[passed])
        np.greater(foregroundMask, 0, out=foregroundMask)
        foregroundMask = label(foregroundMask, connectivity=1).astype(np.int32)
    else:

        if len(logSigma) == 1:
            nucleiDiameter = [logSigma * 0.5, logSigma * 1.5]
        else:
            nucleiDiameter = logSigma
        logMask = nucleiCenters > 150

        win_view_setting = WindowView(nucleiContours.shape, 2000, 500)

        nucleiContours = win_view_setting.window_view_list(nucleiContours)
        padding_mask = win_view_setting.padding_mask()
        mask = win_view_setting.window_view_list(mask)

        maxArea = (logSigma[1]**2) * 3 / 4
        minArea = (logSigma[0]**2) * 3 / 4

        foregroundMask = np.array(
            Parallel(n_jobs=6)(
                delayed(contour_pm_watershed)(img,
                                              sigma=logSigma[1] / 30,
                                              h=logSigma[1] / 30,
                                              tissue_mask=tm,
                                              padding_mask=m,
                                              min_area=minArea,
                                              max_area=maxArea)
                for img, tm, m in zip(nucleiContours, mask, padding_mask)))

        del nucleiContours, mask

        foregroundMask = win_view_setting.reconstruct(foregroundMask)
        foregroundMask = label(foregroundMask, connectivity=1).astype(np.int32)

        if nucleiFilter == 'IntPM':
            int_img = nucleiCenters
        elif nucleiFilter == 'Int':
            int_img = nucleiImage

        print('    ', datetime.datetime.now(), 'regionprops')
        P = regionprops(foregroundMask, int_img)

        def props_of_keys(prop, keys):
            return [prop[k] for k in keys]

        prop_keys = ['mean_intensity', 'area', 'solidity', 'label']
        mean_ints, areas, solidities, labels = np.array(
            Parallel(n_jobs=6)(delayed(props_of_keys)(prop, prop_keys)
                               for prop in P)).T
        del P

        MITh = threshold_otsu(mean_ints)

        minSolidity = 0.8

        passed = np.logical_and.reduce(
            (np.greater(mean_ints,
                        MITh), np.logical_and(areas > minArea,
                                              areas < maxArea),
             np.greater(solidities, minSolidity)))

        # set failed mask label to zero
        foregroundMask *= np.isin(foregroundMask, labels[passed])

        np.greater(foregroundMask, 0, out=foregroundMask)
        foregroundMask = label(foregroundMask, connectivity=1).astype(np.int32)

    return foregroundMask
示例#20
0
    def buttonSave(arg):

        copy = arg[1]
        imageTemp = arg[2]
        filterTry = filterVar.get()
        if (filterTry == 1):
            copy = cv2.GaussianBlur(copy, (5, 5), 0)
        elif (filterTry == 2):
            copy = cv2.Canny(copy, 100, 150)
        elif (filterTry == 3):
            copy = filters.roberts(imageTemp)
        elif (filterTry == 4):
            copy = filters.sato(imageTemp)
        elif (filterTry == 5):
            copy = filters.scharr(imageTemp)
        elif (filterTry == 6):
            copy = filters.sobel(imageTemp)
        elif (filterTry == 7):
            copy = filters.unsharp_mask(copy, radius=30, amount=3)
        elif (filterTry == 8):
            #copy = filters.median(imageTemp, disk(5))
            b, g, r = cv2.split(copy)
            b = filters.median(b, disk(5))
            g = filters.median(g, disk(5))
            r = filters.median(r, disk(5))
            copy = cv2.merge((b, g, r))
        elif (filterTry == 9):
            copy = filters.prewitt(imageTemp)
        elif (filterTry == 10):
            copy = filters.rank.modal(imageTemp, disk(5))
        flag = 0
        if (np.ndim(copy) == 2):
            flag = 0
        else:
            flag = 1

        if (hEsitleme.get() or hGrafik.get()):
            if (flag):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)
            if (hGrafik.get()):
                plt.hist(copy.ravel(), 256, [0, 256])
                plt.show()
            if (hEsitleme.get()):
                copy = cv2.equalizeHist(copy)

        if (uzaysalVars[0].get()):
            reScaleRatio = float(uzaysalVarsInputs[0].get())
            if (np.ndim(copy) == 3):
                b, g, r = cv2.split(copy)
                b = transform.rescale(b, reScaleRatio)
                g = transform.rescale(g, reScaleRatio)
                r = transform.rescale(r, reScaleRatio)
                copy = cv2.merge((b, g, r))
            else:
                copy = transform.rescale(copy, reScaleRatio)

        if (uzaysalVars[1].get()):
            resizeY = float(uzaysalVarsInputs[1].get())
            resizeX = float(uzaysalVarsInputs[2].get())
            if (np.ndim(copy) == 3):
                b, g, r = cv2.split(copy)
                b = transform.resize(
                    b, (b.shape[0] // resizeX, b.shape[1] // resizeY),
                    anti_aliasing=True)
                g = transform.resize(
                    g, (g.shape[0] // resizeX, g.shape[1] // resizeY),
                    anti_aliasing=True)
                r = transform.resize(
                    r, (r.shape[0] // resizeX, r.shape[1] // resizeY),
                    anti_aliasing=True)
                copy = cv2.merge((b, g, r))
            else:
                copy = transform.resize(
                    copy, (copy.shape[0] // resizeX, copy.shape[1] // resizeY),
                    anti_aliasing=True)
        if (uzaysalVars[2].get()):
            copy = transform.swirl(copy, rotation=0, strength=10, radius=120)
        if (uzaysalVars[3].get()):
            copy = transform.rotate(copy,
                                    int(uzaysalVarsInputs[3].get()),
                                    resize=True)
        if (uzaysalVars[4].get()):
            copy = copy[:, ::-1]

        if (yogunlukVars[0].get() or yogunlukVars[1].get()):
            if (yogunlukVars[0].get()):
                startINX = int(yogunlukVars[2].get())
                finishINX = int(yogunlukVars[3].get())
                copy = exposure.rescale_intensity(copy,
                                                  in_range=(startINX,
                                                            finishINX))
            if (yogunlukVars[1].get()):
                startOUTX = int(yogunlukVars[4].get())
                finishOUTX = int(yogunlukVars[5].get())
                copy = exposure.rescale_intensity(copy,
                                                  out_range=(startOUTX,
                                                             finishOUTX))

        morfoTry = morfVar.get()
        morfoGirisN = 0
        if (np.ndim(copy) == 3):
            morfoGirisN = 1

        if (morfoTry == 1):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.area_closing(b, 128, 9)
                g = morphology.area_closing(g, 128, 9)
                r = morphology.area_closing(r, 128, 9)
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.area_closing(copy)
        elif (morfoTry == 2):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.area_opening(b, 128, 9)
                g = morphology.area_opening(g, 128, 9)
                r = morphology.area_opening(r, 128, 9)
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.area_opening(copy)
        elif (morfoTry == 3):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.erosion(b, disk(6))
                g = morphology.erosion(g, disk(6))
                r = morphology.erosion(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.erosion(copy, disk(6))
        elif (morfoTry == 4):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.dilation(b, disk(6))
                g = morphology.dilation(g, disk(6))
                r = morphology.dilation(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.dilation(copy, disk(6))
        elif (morfoTry == 5):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.opening(b, disk(6))
                g = morphology.opening(g, disk(6))
                r = morphology.opening(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.opening(copy, disk(6))
        elif (morfoTry == 6):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.closing(b, disk(6))
                g = morphology.opening(g, disk(6))
                r = morphology.opening(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.opening(copy, disk(6))
        elif (morfoTry == 7):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.white_tophat(b, disk(6))
                g = morphology.white_tophat(g, disk(6))
                r = morphology.white_tophat(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.white_tophat(copy, disk(6))
        elif (morfoTry == 8):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.black_tophat(b, disk(6))
                g = morphology.black_tophat(g, disk(6))
                r = morphology.black_tophat(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.black_tophat(copy, disk(6))
        elif (morfoTry == 10):
            if (morfoGirisN):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)

            copy = exposure.rescale_intensity(copy)
            local_maxima = extrema.local_maxima(copy)
            label_maxima = measure.label(local_maxima)
            copy = color.label2rgb(label_maxima,
                                   copy,
                                   alpha=0.7,
                                   bg_label=0,
                                   bg_color=None,
                                   colors=[(1, 0, 0)])
        elif (morfoTry == 9):
            if (morfoGirisN):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)
            copy = exposure.rescale_intensity(copy)
            h = 0.05
            h_maxima = extrema.h_maxima(copy, h)
            label_h_maxima = measure.label(h_maxima)
            copy = color.label2rgb(label_h_maxima,
                                   copy,
                                   alpha=0.7,
                                   bg_label=0,
                                   bg_color=None,
                                   colors=[(1, 0, 0)])
        arg[1] = copy
        arg[2] = imageTemp
        cv2.imshow("org", copy)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        """
示例#21
0
                          alpha=0.7,
                          bg_label=0,
                          bg_color=None,
                          colors=[(1, 0, 0)])

# We observed in the previous image, that there are many local maxima
# that are caused by the noise in the image.
# For this, we find all local maxima with a height of h.
# This height is the gray level value by which we need to descent
# in order to reach a higher maximum and it can be seen as a local
# contrast measurement.
# The value of h scales with the dynamic range of the image, i.e.
# if we multiply the image with a constant, we need to multiply
# the value of h with the same constant in order to achieve the same result.
h = 0.05
h_maxima = extrema.h_maxima(img, h)
label_h_maxima = label(h_maxima)
overlay_h = color.label2rgb(label_h_maxima,
                            img,
                            alpha=0.7,
                            bg_label=0,
                            bg_color=None,
                            colors=[(1, 0, 0)])

##############################################################
# GRAPHICAL OUTPUT

# a new figure with 3 subplots
fig, ax = plt.subplots(1, 3, figsize=(15, 5))

ax[0].imshow(img, cmap='gray')
示例#22
0
    def search_local_extremum_points_max3(self, history, x_letftop, y_lefttop,
                                          x_rightbottom, y_rightbottom):
        '''
        提取关键点
        :param history: 预测的结果
        :param x_letftop:
        :param y_lefttop:
        :param x_rightbottom:
        :param y_rightbottom:
        :return: 坐标集合,与应用的概率
        '''

        # for train set: t,c,h = -0.5, 50, 0.02
        t_thresh = 0  # -0.5
        c_thresh = 300  # 50
        h_param = 0.01  # 0.02
        low_prob_thresh, high_prob_thresh = CancerMapBuilder.calc_probability_threshold(
            history, t=t_thresh)
        print("low_prob_thresh = {:.4f}, high_prob_thresh = {:.4f}".format(
            low_prob_thresh, high_prob_thresh))

        cmb = CancerMapBuilder(self._params, extract_scale=40, patch_size=256)
        cancer_map = cmb.generating_probability_map(history, x_letftop,
                                                    y_lefttop, x_rightbottom,
                                                    y_rightbottom,
                                                    self._params.GLOBAL_SCALE)

        # cancer_map = filters.gaussian(cancer_map, sigma=0.2)

        h = h_param
        h_maxima = extrema.h_maxima(cancer_map, h, selem=square(7))
        xy = np.nonzero(h_maxima)

        sorted_points = []
        for y, x in zip(xy[0], xy[1]):
            prob = cancer_map[y, x]
            if prob > low_prob_thresh:
                sorted_points.append((prob, x, y))
        sorted_points.sort(key=lambda x: (x[0]), reverse=True)

        resolution = 0.243
        level = 5
        Threshold = 3 * 75 / (resolution * pow(2, level) * 2)  # 3
        result = []
        while len(sorted_points) > 0:
            m = sorted_points.pop(0)
            mx = m[1]
            my = m[2]
            mprob = m[0]
            tx = [mx]
            ty = [my]
            temp = []
            for prob, x, y in sorted_points:
                dist = distance.euclidean([mx, my], [x, y])
                if dist > Threshold:
                    temp.append((prob, x, y))
                else:
                    tx.append(x)
                    ty.append(y)

            mx = np.rint(np.mean(np.array(tx))).astype(np.int)
            my = np.rint(np.mean(np.array(ty))).astype(np.int)

            result.append((mprob, mx, my))
            sorted_points = temp

        result.sort(key=lambda x: (x[0]), reverse=True)

        candidated = []
        count = 0
        for prob, x, y in result:
            if prob > high_prob_thresh or (prob > low_prob_thresh
                                           and count < c_thresh):
                x = x + x_letftop
                y = y + y_lefttop
                candidated.append({"x": 32 * x, "y": 32 * y, "prob": prob})
                count += 1

        return candidated
示例#23
0
local_maxima = extrema.local_maxima(img)
label_maxima = label(local_maxima)
overlay = color.label2rgb(label_maxima, img, alpha=0.7, bg_label=0,
                          bg_color=None, colors=[(1, 0, 0)])

# We observed in the previous image, that there are many local maxima
# that are caused by the noise in the image.
# For this, we find all local maxima with a height of h.
# This height is the gray level value by which we need to descent
# in order to reach a higher maximum and it can be seen as a local
# contrast measurement.
# The value of h scales with the dynamic range of the image, i.e.
# if we multiply the image with a constant, we need to multiply
# the value of h with the same constant in order to achieve the same result.
h = 0.05
h_maxima = extrema.h_maxima(img, h)
label_h_maxima = label(h_maxima)
overlay_h = color.label2rgb(label_h_maxima, img, alpha=0.7, bg_label=0,
                            bg_color=None, colors=[(1, 0, 0)])


##############################################################
# GRAPHICAL OUTPUT

# a new figure with 3 subplots
fig, ax = plt.subplots(1, 3, figsize=(15, 5))

ax[0].imshow(img, cmap='gray', interpolation='none')
ax[0].set_title('Original image')
ax[0].axis('off')
示例#24
0
img = exposure.rescale_intensity(img)

#extract all local maxima
local_maxima = extrema.local_maxima(img)
label_maxima = label(local_maxima)
overlay = color.label2rgb(label_maxima,
                          img,
                          alpha=0.7,
                          bg_label=0,
                          bg_color=None,
                          colors=[(1, 0, 0)])

#extract local maxima with certrain regional contrast
h = 0.05
nb = morphology.selem.disk(radius=3)
h_maxima = extrema.h_maxima(img, h, selem=nb)
label_h_maxima = label(h_maxima)
overlay_hr = color.label2rgb(label_h_maxima,
                             Color_Masked,
                             alpha=0.7,
                             bg_label=0,
                             bg_color=None,
                             colors=[(1, 0, 0)])

#plot results
fig, ax = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True)
ax[0].imshow(Color_Masked, cmap='gray', interpolation='none')
ax[0].set_title('Original image')
ax[0].axis('off')
ax[1].imshow(overlay, interpolation='none')
ax[1].set_title('Local Maxima')
示例#25
0
def h_max_transform(img, h):
    h_maxima = extrema.h_maxima(img, h)
    label_h_maxima = label(h_maxima)
    label_h_maxima[label_h_maxima > 0] = 255
    return label_h_maxima
示例#26
0
            # get the inputs and masks
            inputs = inputs[0].to(device=device)[None,:,:,:]

            net.eval()

            outputs = net(inputs)
        out = outputs[0, 0, :, :].numpy()
        # mask = masks[0, 0, :, :].numpy()
        array = np.where(out < 0.3, 0, out)
        array = out
        # diff = mask-array



        h = 0.2
        h_maxima = extrema.h_maxima(array, h)
        label_h_maxima = label(h_maxima)
        overlay_h = color.label2rgb(label_h_maxima, inputs[0, 0, :, :], alpha=0.7, bg_label=0,
                                    bg_color=None, colors=[(1, 0, 0)])

        coordinates = peak_local_max(array, indices=True)
        coordinates_h = peak_local_max(h_maxima, indices=True)


        fig = plt.figure(dpi=300)
        # ax1 = fig.add_subplot(2, 3, 1)
        # ax1.imshow(inputs[0, 0, :, :].detach().cpu().numpy(), cmap="gray")
        # # ax1.plot(coordinates[:, 1], coordinates[:, 0], 'r+', markersize=10)
        # ax2 = fig.add_subplot(2, 3, 2)
        # ax2.imshow(array, cmap="jet")
        # ax3 = fig.add_subplot(2, 3, 3)
示例#27
0
def detect(img):
    img = np.array(img.convert('RGB'))
    count = 0

    cell_hsvmin = (52, 88, 124
                   )  #Lower end of the HSV range defining the nuclei
    cell_hsvmax = (150, 190, 255
                   )  #Upper end of the HSV range defining the nuclei

    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    Z = hsv.reshape((-1, 3))  #number of chanel, number of row
    # print(Z)

    #Convert to floating point 32 bit
    Z = np.float32(Z)
    # plt.hist(Z),plt.show()
    # histr = cv2.calcHist(Z,[0],None,[256],[0,256])

    # # show the plotting graph of an image
    # plt.plot(histr)
    # plt.show()

    # plt.hist(Z,256,[0,256]),plt.show()

    # plt.scatter(Z[:,0], Z[:,1])
    # plt.show()
    # dc=DominantColor
    #Define the K-means criteria, these are not too important
    #whenever 10 iterations of algorithm is ran, or an accuracy of epsilon = 1.0 is reached, stop the algorithm and return the answer.

    # Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)

    #Define the number of clusters to find
    #นับจาก histrogram มั้ง มันมี4กลุ่ม >> k=4
    K = 4

    #Perform the k-means transformation. What we get back are:
    #*Centers: The coordinates at the center of each 3-space cluster
    #*Labels: Numeric labels for each cluster
    #*Ret: A return code indicating whether the algorithm converged, &c.
    ret, label, center = cv2.kmeans(Z, K, None, criteria, 10,
                                    cv2.KMEANS_RANDOM_CENTERS)

    #Produce an image using only the center colours of the clusters
    center = np.uint8(center)
    khsv = center[label.flatten()]
    khsv = khsv.reshape((img.shape))
    # ShowImage('K-means',khsv,'hsv')

    #Reshape labels for masking
    label = label.reshape(img.shape[0:2])
    # ShowImage('K-means Labels',label,'gray')

    #(Distance,Label) pairs
    nucleus_colour = np.array([139, 106, 192])
    cell_colour = np.array([130, 41, 207])
    # nucleus_colour = np.array([44, 71, 100])
    # cell_colour    = np.array([112, 140,  171])

    nuclei_label = (np.inf, -1)
    cell_label = (np.inf, -1)
    for l, c in enumerate(center):
        # print(l,c)
        dist_nuc = np.sum(
            np.square(c - nucleus_colour))  #Euclidean distance between colours
        if dist_nuc < nuclei_label[0]:
            nuclei_label = (dist_nuc, l)
        dist_cell = np.sum(
            np.square(c - cell_colour))  #Euclidean distance between colours
        if dist_cell < cell_label[0]:
            cell_label = (dist_cell, l)
    nuclei_label = nuclei_label[1]
    cell_label = cell_label[1]
    # print("Nuclei label={0}, cell label={1}".format(nuclei_label,cell_label))

    #Multiply by 1 to keep image in an integer format suitable for OpenCV
    thresh = cv2.bitwise_or(1 * (label == nuclei_label),
                            1 * (label == cell_label))
    thresh = np.uint8(thresh)
    # ShowImage('Binary',thresh,'gray')

    #Remove noise by eliminating single-pixel patches
    kernel = np.ones((3, 3), np.uint8)
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
    # ShowImage('Opening',opening,'gray')

    #Identify areas which are surely foreground
    fraction_foreground = 0.75
    dist = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
    ret, sure_fg = cv2.threshold(dist, fraction_foreground * dist.max(), 255,
                                 0)
    # ShowImage('Distance',dist,'gray')
    # ShowImage('Surely Foreground',sure_fg,'gray')

    #Identify areas which are surely foreground
    h_fraction = 0.1
    dist = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
    maxima = extrema.h_maxima(dist, h_fraction * dist.max())
    # print("Peaks found: {0}".format(np.sum(maxima)))
    #หาค่าความสูง
    #Dilate the maxima so we can see them
    maxima = cv2.dilate(maxima, kernel, iterations=2)
    # ShowImage('Distance',dist,'gray')
    # ShowImage('Surely Foreground',maxima,'gray')

    # Finding unknown region
    unknown = cv2.subtract(opening, maxima)
    # ShowImage('Unknown',unknown,'gray')

    # Marker labelling
    ret, markers = cv2.connectedComponents(maxima)
    # ShowImage('Connected Components',markers,'rgb')

    # Add one to all labels so that sure background is not 0, but 1
    markers = markers + 1

    # Now, mark the region of unknown with zero
    markers[unknown == np.max(unknown)] = 0

    # ShowImage('markers',markers,'rgb')

    dist = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
    markers = skwater(-dist, markers, watershed_line=True)

    # ShowImage('Watershed',markers,'rgb')
    imgout = img.copy()
    imgout[markers == 0] = [0, 0, 255]  #Label the watershed_line

    #x = datetime.datetime.now()
    #st.success(x.strftime("%x"))
    tz = pytz.timezone('Asia/Bangkok')
    now1 = datetime.datetime.now(tz)
    month_name = 'x มกราคม กุมภาพันธ์ มีนาคม เมษายน พฤษภาคม มิถุนายน กรกฎาคม สิงหาคม กันยายน ตุลาคม พฤศจิกายน ธันวาคม'.split(
    )[now1.month]
    thai_year = now1.year + 543
    time_str = now1.strftime('%H:%M:%S')
    st.success("%d %s %d     %s" % (now1.day, month_name, thai_year, time_str))

    # img.save(imgout)
    # cv2.imwrite('output.jpg', imgout)

    for l in np.unique(markers):
        if l == 0:  #Watershed line
            continue
        if l == 1:  #Background
            continue
    #For displaying individual cells
    #temp=khsv.copy()
    #temp[markers!=l]=0
    #ShowImage('out',temp,'hsv')
        temp = label.copy()
        temp[markers != l] = -1
        nucleus_area = np.sum(temp == nuclei_label)
        cell_area = np.sum(temp == cell_label)
        # print("nucleus_area", nucleus_area)
        # print("cell_area",  cell_area)

        # file1.close()
        if nucleus_area / (cell_area + nucleus_area) != 0 and nucleus_area / (
                cell_area + nucleus_area) != 1 and nucleus_area / (
                    cell_area + nucleus_area) != 0.5:
            # output.append(l,nucleus_area/(cell_area+nucleus_area))
            # output.append('\n')
            st.write("N/C ratio is ",
                     nucleus_area / (cell_area + nucleus_area))
            count = count + 1
            # st.markdown("Nucleus fraction for cell {0} is {1}".format(l,nucleus_area/(cell_area+nucleus_area)))
            # test2.append(nucleus_area/(cell_area+nucleus_area))
            # output.append("Nucleus fraction for cell {0} is {1}".format(l,nucleus_area/(cell_area+nucleus_area)))

            # test1 = "\n".join(output)

            # output = "\n".join(output)
            # print("Nucleus fraction for cell {0} is {1} ".format(l,nucleus_area/(cell_area+nucleus_area)))
    # print(*output, sep = "\n")
    st.write("Sum of cell is ", count)
    return img
示例#28
0
def evaluate(model, eval_loader, dist_threshold=3):
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    runnning_dice_vec = 0
    runnning_prec_vec = 0
    runnning_rec_vec = 0
    dice_vec = []
    model.eval()
    for i, (image, mask, name, x, y) in enumerate(eval_loader):

        name = name[0]
        image = image[0].to(device=device)[None, :, :, :]

        with torch.no_grad():
            outputs = model(image)

        out = outputs[0, 0, :, :].cpu().numpy()
        array = np.where(out < 0.3, 0, out)

        h = 0.3
        h_maxima = extrema.h_maxima(array, h)
        label_h_maxima = label(h_maxima)

        coordinates = peak_local_max(label_h_maxima, indices=True)

        # fig = plt.figure(dpi=300)
        # ax1 = fig.add_subplot(1, 3, 1)
        # ax1.imshow(image[0, 0, :, :].detach().cpu().numpy(), cmap="gray")
        # ax1.plot(coordinates[:, 1], coordinates[:, 0], 'r+', markersize=10)
        # ax2 = fig.add_subplot(1, 3, 2)
        # ax2.imshow(outputs[0, 0, :, :].detach().cpu().numpy(), cmap="gray")
        # ax3 = fig.add_subplot(1, 3, 3)
        # # ax3.imshow(inputs[0, 0, :, :].detach().cpu().numpy(), cmap="gray")
        # # ax3.imshow(outputs[0, 0, :, :].detach().cpu().numpy(), cmap="jet", alpha=0.3)
        # ax3.imshow(array)
        # plt.show()

        gt_x = x
        gt_y = y

        pred_x = coordinates[:, 1]
        pred_y = coordinates[:, 0]

        # fig = plt.figure(dpi=300)
        # ax1 = fig.add_subplot(1, 1, 1)
        # ax1.imshow(image[0, 0, :, :].detach().cpu().numpy(), cmap="gray")
        # ax1.plot(gt_x, gt_y, 'g+', linewidth=3, markersize=12)
        # ax1.plot(pred_x, pred_y, 'm+', linewidth=3, markersize=12)
        # plt.show()

        dist_matrix = np.zeros((len(gt_x), len(pred_x)))
        for row, (g_x, g_y) in enumerate(zip(gt_x, gt_y)):
            for col, (p_x, p_y) in enumerate(zip(pred_x, pred_y)):
                x = abs(g_x - p_x)
                y = abs(g_y - p_y)
                dist_matrix[row, col] = math.sqrt((x * x) + (y * y))

        min_dists = np.amin(dist_matrix, axis=0)

        tp = 0
        fp = 0
        for dist in min_dists:
            if dist <= dist_threshold:
                tp += 1
            else:
                fp += 1
        tp = len(gt_x) if tp > len(gt_x) else tp
        fn = len(gt_x) - tp
        if (tp + fp) == 0:
            precision = 0
        else:
            precision = tp / (tp + fp)
        recall = tp / (tp + fn)
        dice = (2 * tp) / (2 * tp + fp + fn)
        runnning_dice_vec += dice
        runnning_prec_vec += precision
        runnning_rec_vec += recall

        dice_vec.append(dice)

        print(
            f"{name}, TP: {tp}, FP: {fp}, FN: {fn}, precision: {precision}, recall: {recall}, dice: {dice}"
        )
        # print(f"Iteration: {i} of {len(eval_loader)}, image: {name}")

    # dice_vec.append(runnning_dice_vec / len(eval_loader))
    # prec_vec.append(runnning_prec_vec / len(eval_loader))
    # rec_vec.append(runnning_rec_vec / len(eval_loader))

    prec_result = runnning_prec_vec / len(eval_loader)
    rec_result = runnning_rec_vec / len(eval_loader)
    dice_result = runnning_dice_vec / len(eval_loader)

    return prec_result, rec_result, dice_result, dice_vec
示例#29
0
img = exposure.rescale_intensity(img)

#extract local maxima
local_maxima = extrema.local_maxima(img_gs_inv)
label_maxima = label(local_maxima)
overlay = color.label2rgb(label_maxima,
                          img_gs_inv,
                          alpha=0.7,
                          bg_label=0,
                          bg_color=None,
                          colors=[(1, 0, 0)])

#local maxima with certrain contrast
h = 0.05
ding = morphology.selem.disk(radius=3)
h_maxima = extrema.h_maxima(img, h, selem=ding)
label_h_maxima = label(h_maxima)
overlay_h = color.label2rgb(label_h_maxima,
                            img,
                            alpha=0.7,
                            bg_label=0,
                            bg_color=None,
                            colors=[(1, 0, 0)])

# a new figure with 3 subplots
fig, ax = plt.subplots(1, 3, figsize=(15, 5), sharex=True, sharey=True)

ax[0].imshow(Color_Masked, cmap='gray', interpolation='none')
ax[0].set_title('Original image')
ax[0].axis('off')
    #binar_data=img_as_float(binar_data)
    label_data = label(binar_data)  #označení buněk v masce
    #plt.imshow(label_data,cmap=plt.cm.nipy_spectral)

    output = np.load('/Users/betyadamkova/Desktop/final/model 8/output/' +
                     'output' + str(it) + '.npy')
    output = output[0, 0, :, :]
    inverse_output = util.invert(output)  #inverzní distanšní mapa
    binar_output = output > 1.3
    binar_output = remove_small_holes(remove_small_objects(binar_output, 15),
                                      12)
    #plt.imshow(inverse_output,cmap="gray")

    ################### marker controlled watershed
    h = 2  #h= minimální výška extrahovaných maxim
    h_maxima = extrema.h_maxima(output, h)  #nalezení středu buněk
    marker = label(h_maxima)  #označení stredu buněk
    #plt.imshow(h_maxima,cmap="gray")
    labels = watershed(
        inverse_output, marker, mask=binar_output
    )  #vstup do funkce: inverní distanční mapa, označené středy, binární
    #plt.imshow(labels,cmap=plt.cm.nipy_spectral)

    ################ random walker segmentation
    h = 2
    h_maxima = extrema.h_maxima(output, h)  #středy buněk
    marker2 = label(h_maxima)  #označení buněk
    marker2[~binar_output] = -1  #bunky=0, okoli=-1, středy buněk označené
    #plt.imshow(marker2,cmap="gray")
    if (np.amax(marker2)).astype(
            np.int