def thresholding(image, threshold):
	if isinstance(threshold,int) or isinstance(threshold,float):
		thresh = threshold
	elif isinstance(threshold,str):
		# Assume its Ok to use the same threshold for each layer.
		parsestr = threshold.split(" ")
		parsestr = [i.lower() for i in parsestr]
		parsestr = set(parsestr)
		if "otsu" in parsestr:
			if "global" in parsestr:
				ind = np.argmax([np.mean(i) for i in image])
				thresh = filters.threshold_otsu(image[ind])
				print thresh, ind
			elif "local" in parsestr:
				radius = int(parsestr[2])
				mask = morphology.disk(radius)
				thresh = filters.rank.otsu(image,mask)
		if "li" in parsestr:
			thresh = filters.threshold_li(image)
		if "yen" in parsestr:
			thresh = filters.threshold_yen(image)

	threshinds = image<thresh
	binimg =  np.ones(image.shape)
	binimg[threshinds] = 0
	return binimg, thresh
Example #2
0
def cont(imagen, depth=2**16, gaussian=3, screenpercent=0.7,t=0):

    imagen = gaussian_filter(imagen, gaussian)

    if t==0:
        otsu = threshold_otsu(imagen, depth)
    elif t==1:
        otsu = filters.threshold_isodata(imagen, depth)
    else:
        otsu = filters.threshold_li(imagen)
    imagen = binarizar(imagen, otsu)
    imagen = gaussian_filter(imagen, gaussian)

    contours = measure.find_contours(imagen, 1)
    centro = np.asanyarray([1280*0.5, 960*0.5])
    while len(contours) > 1:
        if sum(np.abs(centro - contours[1].mean(axis=0)) < [1280*screenpercent*0.5, 960*screenpercent*0.5]) != 2:
            del contours[1]
        elif sum(np.abs(centro - contours[0].mean(axis=0)) < [1280*screenpercent*0.5, 960*screenpercent*0.5]) != 2:
            del contours[0]
        else:
            if contours[1].size < contours[0].size:
                del contours[1]
            else:
                del contours[0]
    return imagen, contours[0]
def main(filename,outfile):
    # Open geotiff file:
    geoimg = gdal.Open(filename, gdal.GA_ReadOnly)
    image = geoimg.ReadAsArray().astype(np.uint16)
    rows = geoimg.RasterYSize
    cols = geoimg.RasterXSize
    if geoimg.RasterCount>1:
        img = image.max(axis=0)
    else:
        img = image.copy();
    mbi = proc_mbi(img)
    save_geotiff(outfile, mbi, geoimg, gdal.GDT_Float64)
    # otsu = filters.threshold_otsu(mbi,1024)
    # mbi_bw = (mbi > otsu)
    # save_geotiff('/Users/jorge/Documents/LSE/Sample1m/Sample1m_mbiBW_otsu.tif', mbi_bw, geoimg, gdal.GDT_Byte)
    # yen = filters.threshold_yen(mbi,1024)
    # mbi_bw = (mbi > yen)
    # save_geotiff('/Users/jorge/Documents/LSE/Sample1m/Sample1m_mbiBW_yen.tif', mbi_bw, geoimg, gdal.GDT_Byte)
    # isodata = filters.threshold_isodata(mbi,1024)
    # mbi_bw = (mbi > isodata)
    # save_geotiff('/Users/jorge/Documents/LSE/Sample1m/Sample1m_mbiBW_isodata.tif', mbi_bw, geoimg, gdal.GDT_Byte)
    li = filters.threshold_li(mbi)
    mbi_bw = (mbi > li)
    save_geotiff('/Users/jorge/Documents/LSE/Sample1m/Sample1m_mbiBW_li.tif', mbi_bw, geoimg, gdal.GDT_Byte)
    # mbi_bw = (mbi > 0)
    # save_geotiff('/Users/jorge/Documents/LSE/Sample1m/Sample1m_mbiBW_minVal.tif', mbi_bw, geoimg, gdal.GDT_Byte)
    return True
def process_file(filename):
    """
    Main processing function; loads image file, runs some simple
    filters, and returns labelled image array
    """
    data = load_data(filename)
    print("Loaded data", data.shape)
    # Grayscale
    filt = data.mean(axis=-1)
    # Basic threshold
    print("Running basic thresholding...")
    bw = filt > skfilt.threshold_li(filt)
    labels = skmeas.label(bw)
    return labels
Example #5
0
def gen_background_mask( img ):
	"""
	Utility function for making MRI image masks to remove the background via threshold filter.

	Parameters
	----------
	img:	     Numpy array containing the CEST data images
                     Array must be ordered as [ phe2, phe1, npts]

	Returns
	-------
	
	A 2D image mask.

	"""
		
	if   len( img.shape ) == 3: t = img[0]
	elif len( img.shape ) == 2: t = img

	mask = img > filters.threshold_li(t)

	return mask
print(fi)

im =io.imread(fi)


print(im.shape, im.dtype)

binThrAd = filters.threshold_adaptive(im,21, method='median', offset=0, mode='reflect', param=None)

thrIso = filters.threshold_isodata(im, nbins=256, return_all=False)
binIso = im > thrIso
tiIso = "Iso %d" % thrIso
print(thrIso)

thrLi = filters.threshold_li(im)
binLi = im > thrLi
tiLi = "Li %d" % thrLi

thrOtsu = filters.threshold_otsu(im, nbins=256)
binOtsu = im > thrOtsu
tiOtsu = "Otsu %d" % thrOtsu

thrYen = filters.threshold_yen(im, nbins=256)
binYen = im > thrYen
tiYen = "Yen %d" % thrYen

# cImg = displayImg(binYen, name='coins-binYen')
# cImg.show()

fPan = displayAll([im, binThrAd, binIso, binLi, binOtsu, binYen], ["Original", "Adaptive", tiIso, tiLi, tiOtsu, tiYen], fSize=12)
from skimage import data, color, filters
import matplotlib.pyplot as plt
from skimage.morphology import disk
import skimage.filters.rank as sfr

original_image = color.rgb2gray(data.camera())
plt.imshow(original_image, cmap=plt.cm.gray)

thresh = []
thresh.append(filters.threshold_otsu(original_image))
thresh.append(filters.threshold_yen(original_image))
thresh.append(filters.threshold_li(original_image))
thresh.append(filters.threshold_isodata(original_image))

filtered_images = []
for t in thresh:
    dst = (original_image <= t) * 1.0  # 根据阈值进行分割
    filtered_images.append(dst)

name_list = ['otsu', 'yen', 'li', 'isodata']

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8))
axes = axes.ravel()
for ax, img, name in zip(axes, filtered_images, name_list):
    ax.imshow(img, cmap=plt.cm.gray, interpolation='nearest')
    ax.set_title(name)

for ax in axes:
    ax.axis('off')

fig.tight_layout()
Example #8
0
def thresholding_optimal(img):
    return img > filters.threshold_li(img)
Example #9
0
    def watershed_scikit(self,
                         input_img,
                         cell_size=None,
                         first_threshold=None,
                         second_threshold=None):

        img_uint8 = cv2.copyMakeBorder(input_img,
                                       5,
                                       5,
                                       5,
                                       5,
                                       cv2.BORDER_CONSTANT,
                                       value=0)

        med_scikit = median(img_uint8, disk(1))
        thresh = threshold_li(med_scikit)
        binary = med_scikit > thresh
        filled = ndimage.binary_fill_holes(binary)
        filled_blurred = gaussian(filled, 1)
        filled_int = (filled_blurred * 255).astype('uint8')

        # #         edge_sobel = sobel(img_uint8)
        # #         enhanced = 50*edge_sobel/edge_sobel.max() + img_uint8
        # #         enhanced.astype('uint8')
        # #         med_scikit = median(img_uint8, disk(5))
        thresh = threshold_li(filled_int)
        binary = filled_int > thresh
        filled = ndimage.binary_fill_holes(binary)
        filled_int = binary_opening(filled, disk(5))
        filled_int = ndimage.binary_fill_holes(filled_int)
        #         filled_blurred = gaussian(openeed, 3)

        #         thresh = threshold_li(filled_int)
        #         binary = filled_int > thresh
        #binary = binary_erosion(filled_int, disk(5))
        distance = ndimage.distance_transform_edt(filled_int)
        binary1 = distance > first_threshold
        distance1 = ndimage.distance_transform_edt(binary1)
        binary2 = distance1 > second_threshold

        labeled_spots, num_features = label(binary2)
        spot_labels = np.unique(labeled_spots)

        spot_locations = ndimage.measurements.center_of_mass(
            binary2, labeled_spots, spot_labels[spot_labels > 0])

        mask = np.zeros(distance.shape, dtype=bool)
        if spot_locations:
            mask[np.ceil(np.array(spot_locations)[:, 0]).astype(int),
                 np.ceil(np.array(spot_locations)[:, 1]).astype(int)] = True
        markers, _ = ndimage.label(mask)
        labels = watershed(-distance,
                           markers,
                           mask=binary,
                           compactness=0.5,
                           watershed_line=True)
        boundary = find_boundaries(labels,
                                   connectivity=1,
                                   mode='thick',
                                   background=0)
        boundary_img = (255 *
                        boundary[3:boundary.shape[0] - 3,
                                 3:boundary.shape[1] - 3]).astype('uint8')
        resized_bound = cv2.resize(boundary_img,
                                   (input_img.shape[1], input_img.shape[0]))
        filled1 = ndimage.binary_fill_holes(resized_bound)
        mask = (255 * filled1).astype('uint8') - resized_bound
        boundary = resized_bound.astype('uint8')

        return boundary, mask
Example #10
0
def test_acc(image_name,nnet_model=nnet):
    angle_indicator = int(image_name.split('_')[1])
    image = misc.imread('test_sample/' + image_name + '.jpg',flatten = True).astype(float)
    image_rgb = misc.imread('test_sample/' + image_name + '.jpg')
    image_float = image_rgb.astype(float)
    image_mask = misc.imread('train_masks/' + image_name + '_mask.gif',flatten = True)
    image_mask = image_mask/255
#io.imshow(image_mask)
    image_index = np.where(image >= 0)
    sobel = filters.sobel(image)   # working
#io.imshow(sobel)
    sobel_blurred = filters.gaussian(sobel,sigma=1)  # Working
#io.imshow(sobel_blurred)
    canny_filter_image = canny(image/255.)
#io.imshow(canny_filter_image)
#    threshold_niblack_11 = filters.threshold_niblack(sobel_blurred,201)
#io.imshow(threshold_niblack)
    threshold_li = filters.threshold_li(image)
    mask_li = image > threshold_li
#io.imshow(mask)
    sobel_h = filters.sobel_h(image)
    sobel_v = filters.sobel_v(image)
    laplace = filters.laplace(image)
    threshold_local_51 = filters.threshold_local(image,51)
    mask_local_51 = image > threshold_local_51
#io.imshow(mask)
    df = pd.DataFrame()
    df['l1_dist_y'] = abs(image_index[0] - 639.5)/639.5
    df['l1_dist_x'] = abs(image_index[1] - 958.5)/958.5
    df['l2_dist'] = np.sqrt((df.l1_dist_y)**2 + (df.l1_dist_x)**2)/np.sqrt(2)
    df['grey_values'] = image.reshape((1,1918*1280))[0]/255.
    df['red_values'] = image_rgb.reshape((3,1918*1280))[0]/255.
    df['blue_values'] = image_rgb.reshape((3,1918*1280))[1]/255.
    df['green_values'] = image_rgb.reshape((3,1918*1280))[2]/255.
    df['red_float'] = image_float.reshape((3,1918*1280))[0]/255.
    df['blue_float'] = image_float.reshape((3,1918*1280))[1]/255.
    df['green_float'] = image_float.reshape((3,1918*1280))[2]/255.
    df['sobel_blurred'] = sobel_blurred.reshape((1,1918*1280))[0]/255.
    df['canny_filter_image'] = canny_filter_image.reshape((1,1918*1280))[0].astype(int)
    df['sobel_h'] = sobel_h.reshape((1,1918*1280))[0]/255.
    df['sobel_v'] = sobel_v.reshape((1,1918*1280))[0]/255.
    df['laplace'] = laplace.reshape((1,1918*1280))[0]/511.
    df['threshold_local_51'] = mask_local_51.reshape((1,1918*1280))[0].astype(int)
#    df['threshold_niblack_11'] = threshold_niblack_11.reshape((1,1918*1280))[0]#/255.
    df['threshold_li'] = mask_li.reshape((1,1918*1280))[0].astype(int)
    for i in range(1,17):
        if i == angle_indicator:
            df['angle_indicator_' + str(i)] = 1
        else:
            df['angle_indicator_' + str(i)] = -1
    df['mask'] = image_mask.reshape((1,1918*1280))[0]
    df['mask'] = df['mask']
    df['pred_mask'] = nnet_model.predict(X = df[[col for col in img_df.columns if col != 'mask']])
    z = skm.confusion_matrix(df['mask'],df['pred_mask'])
    accuracy = 100*(z[0][0] + z[1][1])/float(sum(sum(z)))
    print 'Accuracy:', accuracy
    precision = 100*(z[1][1])/float(z[0][1] + z[1][1])
    print 'Precision:', precision
    recall = 100*(z[1][1])/float(z[1][0]+z[1][1])
    print 'Recall:', recall
    act_mask = np.array(df['mask'])
    act_mask = act_mask.reshape((1280,1918))
    pred_mask = np.array(df['pred_mask']).astype(float)
    pred_mask = pred_mask.reshape((1280,1918))
    io.imshow_collection([img_rgb,act_mask,pred_mask])
    return df
Example #11
0
# image_show(text_segmented)
# pylab.show()
#
# text_segmented = text > 10
# image_show(text_segmented)
# pylab.show()
#
# text_segmented = text > 20
# image_show(text_segmented)
# pylab.show()

# text_local = filters.threshold_local(text, block_size=51, offset=10)
# image_show(text > text_local)
# pylab.show()

text_otsu = filters.threshold_otsu(text)
image_show(text <= text_otsu)
pylab.show()

text_li = filters.threshold_li(text)
image_show(text <= text_li)
pylab.show()

text_yen = filters.threshold_yen(text)
image_show(text > text_yen)
pylab.show()

text_iso = filters.threshold_isodata(text)
image_show(text > text_iso)
pylab.show()
Example #12
0
def _extract_roi(image, axis=-1):
    max_frame = np.max(image, axis=axis)
    initial_mask = max_frame > threshold_li(max_frame)
    regions = ndi.label(initial_mask)[0]
    region_sizes = np.bincount(np.ravel(regions))
    return regions == (np.argmax(region_sizes[1:]) + 1)
Example #13
0
def threshold_fiber(img_fish, t_fiber=None, z_first=False, verbose=False):
    """Segment the muscle fiber from a 3D FISH microscopy image.

    Return a mask containing the extent of the muscle fiber from a 3D FISH 
    image. If `t_fiber` is provided, use that for thresholding. Otherwise, 
    automatically determine the threshold value using Li's method.

    Parameters:

    img_fish: np.array, 3D
        A 3D numpy array containing signal from the FISH channel, organized 
        as [x, y, z] (unless `z_first` is set to True).


    Optional:
    
    t_fiber: float or str (default None)
        Threshold to use for binarization of the FISH image, from 0 to 1. 
        If not set, automatically determine this threshold using Li's method. 
        Alternatively, if set to 'last', the final z-slice of the image will 
        be thresholded, and this mask will be used for the entire z-stack.
    
    z_first: bool (default False)
        If True, treat `img_fish` as image with dimensions [z, x, y].

    verbose: bool (default False)
        If True, print progress to stdout.
    """

    if verbose:
        print('Segmenting fiber...')

    # image preprocessing
    if z_first:
        # switch to (x, y, z)
        img_fish = img_fish.transpose(1, 2, 0)

    img_avg = su.normalize_image(img_fish)
    img_blur = filters.gaussian(img_avg, (10, 10, 1))

    # get threshold using method determined from value of t_fiber
    if t_fiber is None:
        thresh = filters.threshold_li(img_blur)
    elif type(t_fiber) == float:
        thresh = t_fiber
    elif t_fiber == 'last':
        thresh = filters.threshold_li(img_blur[:, :, -1])
    else:
        raise TypeError('`t_fiber` argument not recognized. \
            Must be either float or "last".')

    if verbose:
        print('Fiber threshold: ' + str(thresh))

    # binarize
    bin_fiber = np.where(img_blur > thresh, 1, 0)

    if t_fiber == 'last':
        # only use the last frame to define the fiber volume
        # this is a last resort option to deal with glare in the RNA channel
        # warning: densities will be underestimated
        for z in range(bin_fiber.shape[2]):
            bin_fiber[:, :, z] = bin_fiber[:, :, -1]

        if verbose:
            print('OVERRIDE: using final frame mask for entire z-stack.')

    # keep only largest object in the image
    fiber_labeled, n_labels = morphology.label(bin_fiber, return_num=True)
    label_sizes = {
        i: np.count_nonzero(np.where(fiber_labeled == i, 1, 0))
        for i in range(1, n_labels + 1)
    }
    fiber_idx = max(label_sizes, key=label_sizes.get)
    mask = np.where(fiber_labeled == fiber_idx, 1, 0)

    if z_first:
        # switch back to (z, x, y)
        mask = mask.transpose(2, 0, 1)

    return mask
    def detector_callback(self, preprocessed_pc):
        """
        Main callback method of the detector that executes the procedure of
        automatic thresholding, clustering, volume correction and some
        calculations to extract the volume, boundaries and centers of the gaps.

        Parameters
        ----------
        preprocessed_pc : sensor_msgs.pointcloud2
            Preprocessed point cloud generated by the preprocessing node.

        Notes
        -----
        After each procedure step a point cloud is published over the
        publishers defined in __init__ as well as some visualization Markers
        for RVIZ.

        """
        points = helpers.PC2_to_numpy_array(preprocessed_pc)
        self.frame_id = preprocessed_pc.header.frame_id

        # ----- AUTOMATIC THRESHOLDING TO FIND GAPS -----
        depth_axis_pts = points[:, self.depth_axis]

        if(self.automatic_thresholding == 0):
            try:
                threshold = threshold_minimum(depth_axis_pts)
            except RuntimeError:
                rospy.logwarn("threshold_minimum was unable to find two " +
                              "maxima in histogram!")
                return
        elif(self.automatic_thresholding == 1):
            threshold = threshold_li(depth_axis_pts)
        elif(self.automatic_thresholding == 2):
            threshold = threshold_yen(depth_axis_pts)
        elif(self.automatic_thresholding == 3):
            threshold = threshold_otsu(depth_axis_pts, self.otsu_bins)

        device_surface_pts = points[depth_axis_pts <= threshold]
        self.surface_height = np.median(device_surface_pts[:, self.depth_axis])

        points = points[depth_axis_pts > threshold]

        # ----- PUBLISHING OF THE THRESHOLDED CLOUD -----
        thresholded_cloud = helpers.numpy_array_to_PC2(points, self.frame_id)
        self.thresholded_cloud_pub.publish(thresholded_cloud)

        # ----- CLUSTERING THE GAPS -----
        clustering_switch = {
            0: self.kmeans,
            1: self.birch,
            2: self.dbscan,
            3: self.hdbscan
        }

        cluster_algorithm = clustering_switch[self.clustering]
        labels = cluster_algorithm(points)
        labels_T = np.array([labels]).T
        clustered_points = np.append(points, labels_T, axis=1)

        color_list = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0],
                      [1.0, 1.0, 1.0], [0.5, 0.5, 0.5], [1.0, 0.5, 0.5],
                      [0.5, 1.0, 0.5], [0.5, 0.5, 1.0]]

        clusters = []
        colored_clusters = []
        # check for each cluster if there are enough points in the cluster
        for i in set(labels):
            cluster = clustered_points[clustered_points[:, 3] == float(i)]
            cluster = cluster[:, [0, 1, 2]]

            # create seperate list of points to visualize clusters
            for cluster_point in cluster:
                try:
                    color = np.array(color_list[i])
                except IndexError:
                    color = np.array([0.0, 0.0, 0.0])
                point_with_color = np.append(cluster_point, color)
                colored_clusters.append(point_with_color)

            # To construct a convex hull a minimum of 4 points is needed
            num_of_points, dim = cluster.shape
            if(num_of_points >= 4):
                clusters.append(cluster)

        # ----- PUBLISHING OF CLUSTERS-----
        clustered_cloud = helpers.XYZRGB_to_PC2(
            colored_clusters, self.frame_id)
        self.clustered_cloud_pub.publish(clustered_cloud)

        # ----- VOLUME CORRECTION -----
        volume_corrected_clusters = []
        num_vol_corrected_pts = 0
        volume_corrected_pts_tuple = ()
        for cluster in clusters:
            hull = ConvexHull(cluster, qhull_options="QJ")

            # Map from vertex to point in cluster
            vertices = []
            for vertex in hull.vertices:
                x, y, z = cluster[vertex]
                vertices.append([x, y, z])

            gap = cluster.tolist()
            for vertex in vertices:
                # For each vertex, add a new point to the gap with the height
                # of the surface and the other axes corresponding to the vertex
                if(self.depth_axis == 0):
                    volume_point = [self.surface_height, vertex[1], vertex[2]]
                elif(self.depth_axis == 1):
                    volume_point = [vertex[0], self.surface_height, vertex[2]]
                elif(self.depth_axis == 2):
                    volume_point = [vertex[0], vertex[1], self.surface_height]

                gap.append(volume_point)
                num_vol_corrected_pts = num_vol_corrected_pts + 1

            volume_corrected_clusters.append(np.array(gap))
            volume_corrected_pts_tuple = volume_corrected_pts_tuple + \
                (num_vol_corrected_pts,)
            num_vol_corrected_pts = 0

        # ---- CALCULATING CONVEX HULLS OF GAPS AND THEIR CENTER -----
        convex_hulls_and_info = helpers.calculate_convex_hulls_and_centers(
            volume_corrected_clusters)

        # ---- FILTER BASED ON VOLUME -----
        self.gaps = []
        for gap_info in convex_hulls_and_info:
            gap_volume = gap_info[3]

            # convert cm^3 to m^3
            gap_volume = gap_volume * 1000000.0

            if(self.min_gap_volume <= gap_volume <= self.max_gap_volume):
                self.gaps.append(gap_info)

        # ----- PUBLISHING THE MARKERS TO RVIZ -----
        if not len(self.gaps) == 0:
            gap_info = zip(*self.gaps)
            centers, vertices, simplices, volumes, num_of_points = gap_info

            convex_hull_marker = visualization.draw_convex_hull(
                simplices, self.frame_id)
            self.convex_hull_marker_pub.publish(convex_hull_marker)

            centers_marker = visualization.draw_centers(centers, self.frame_id)
            self.centers_marker_pub.publish(centers_marker)

            volume_text_marker = visualization.draw_volume_text(
                volumes, centers, self.frame_id)
            self.volume_text_marker_pub.publish(volume_text_marker)

        # ----- EVALUATION -----
        if(self.create_evaluation):
            num_of_points = np.subtract(num_of_points, num_vol_corrected_pts)
            evaluation_info = zip(num_of_points, volumes, centers)
            helpers.evaluate_detector(evaluation_info)
            self.create_evaluation = False
Example #15
0
def li_func(img_slice):
    return filters.threshold_li(img_slice)
Example #16
0
matplotlib.rcParams['font.size'] = 9
img_orig = '/home/andrea/Desktop/20160713_NCP_GO_Talos_121.jpg'
img_lowpass = '******'
out_dir = '/home/andrea/Desktop/test'
if not os.path.isdir(out_dir):
    os.makedirs(out_dir)
os.chdir(out_dir)
# print('Processing original')
# image_orig = imread(img_orig, as_grey=True, flatten = True)
# thresh_orig = threshold_isodata(image_orig)
# binary_orig = image_orig > thresh_orig
print('Processing lowpass isodata')
image = imread(img_lowpass, as_grey=True, flatten=True)
thresh_isodata = threshold_isodata(image)
thresh_otsu = threshold_otsu(image)
thresh_li = threshold_li(image)
thresh_yen = threshold_yen(image)
thresh_adaptive = threshold_adaptive(image, 3)
binary_isodata = image > thresh_isodata
binary_otsu = image > thresh_otsu
binary_li = image > thresh_li
binary_adaptive = image > thresh_adaptive
binary_yen = image > thresh_yen
# edges = canny(image_orig/255.)
# fill_image = ndi.binary_fill_holes(edges)
imshow(binary_isodata)
imshow(binary_otsu)
imshow(binary_yen)
imshow(binary_li)
imshow(binary_adaptive)
Example #17
0
    dataset = 1
    t0 = time()
    data0 = np.load('data/20190401_GASP_PHANTOM/set%d_tr6_te3.npy' % dataset)
    data1 = np.load('data/20190401_GASP_PHANTOM/set%d_tr12_te6.npy' % dataset)
    data2 = np.load('data/20190401_GASP_PHANTOM/set%d_tr24_te12.npy' % dataset)
    print(time() - t0)

    print(data0.shape)  # [Height, Width, Coil, Avg, PCs]

    data = np.concatenate(
        (data0[..., None], data1[..., None], data2[..., None]), axis=-1)
    data = np.mean(data, axis=3)  # [Height, Width, Coil, PCs, TRs]

    # Create a mask of the phanton
    band_free = gs_recon(data[:, :, 0, ::4, 0], pc_axis=-1)
    thresh = threshold_li(np.abs(band_free))
    mask = np.abs(band_free) > thresh

    # Apply mask to data
    mask0 = np.tile(mask, (data.shape[2:] + (
        1,
        1,
    ))).transpose((3, 4, 0, 1, 2))
    data = data * mask0

    print(data.shape[:-2])
    data = np.reshape(data, data.shape[:-2] +
                      (-1, ))  # [Height, Width, Coil, PCs x TRs]
    data = np.moveaxis(data, 2, 0)  # [Coil, Height, Width, PCs x TRs]
    data = data.transpose((0, 3, 2, 1))  # [Coil,  PCs x TRs, Width, Height]
Example #18
0
    ifft = lambda x0: np.fft.fftshift(np.fft.ifft2(
        np.fft.ifftshift(x0, axes=(0, 1)), axes=(0, 1)),
                                      axes=(0, 1))

    # Put into imspace
    ims = ifft(data)

    plt_opts = {
        'vmin': 0,
        'vmax': 2.5,
    }

    # Look at only pixels that have strong enough signal
    sos = np.sqrt(np.sum(np.abs(ims)**2, axis=-2))  # across time
    thresh = threshold_li(sos)
    mask = sos > thresh / 2

    # Run on each coil
    # T1s = np.zeros(data.shape[:2])
    T1s = []
    A, B = 1, -2
    for cc in range(ims.shape[-1]):

        t0 = time()
        ims0 = ims[..., cc]
        T1, A, B, niter, err = t1iter(ims0,
                                      t,
                                      mask=mask[..., cc],
                                      T10=1,
                                      A0=A,
Example #19
0
 def get_threshold(self, image):
     return Threshold.color_in_range(image, threshold_li(image))
def optimize(img):
    img = gaussian(img)
    thresh = threshold_li(img)
    img = img > thresh

    return img
def binaryMask(image):
    threshold = skf.threshold_li(image)
    return image > threshold
def binarize(img):
    thresh = threshold_li(img)
    img = img > thresh
    return img
Example #23
0
def bacteria_watershed(
        segs,
        maxsize=1000,  #uint16((5*2)/(pix2mic**2))  ### max area
        minsize=200,  #uint16((0.5*0.1)/(pix2mic**2))    ### min area
        absolwidth=1,
        thr_strength=2.,
        phase_contrast=None,
        fix_thr=None):
    min_av_width = 1
    segs2 = {}  # here images after watershed
    thresh_array = []
    #    for ch_n, img0 in segs.items():
    #        thresh_array.append(skfilt.threshold_minimum(img0.flatten()))
    #    med, mad = get_med_and_mad(thresh_array)
    #    threshold_int = med+3*mad

    for ch_n, img0 in segs.items():
        if fix_thr is None:
            thresh = skfilt.threshold_li(
                np.concatenate([s.flatten() for s in segs.values()]))

        else:
            thresh_thr = fix_thr

        bw0 = img0 > thresh
        bw1 = ndi.morphology.binary_erosion(bw0)
        bw2 = ndi.morphology.binary_dilation(bw0)
        bw3 = bw2 ^ bw1

        # perform distance transform on filtered image
        dist = ndi.distance_transform_edt(bw2)

        # create markers for watershed
        markers = np.zeros(img0.shape, dtype=bool)

        markers[dist >= absolwidth] = True
        markers = ndi.label(markers)[0]
        #markers[markers>=1]= markers[markers>=1]+1
        #markers[bw3] = 0

        # Perform watershed
        labeled_bacteria = skseg.watershed(-dist, markers, mask=bw2)
        #labeled_bacteria = ndi.binary_fill_holes(segmentation)# != 1)

        ### now filter bacteria for size and width
        dist = ndi.distance_transform_edt(labeled_bacteria > 0)

        newbac = np.zeros(labeled_bacteria.shape, dtype=labeled_bacteria.dtype)

        stats = dict(
            num_rejected_av_width=0,
            num_rejected_area=0,
        )

        label = 0
        for region in regionprops(labeled_bacteria):
            masked_bac = labeled_bacteria == region.label
            skel = skeletonize(masked_bac)
            av_width_skel = np.mean(dist[skel])
            if av_width_skel < min_av_width:
                stats["num_rejected_av_width"] += 1
                continue
            if maxsize > region.area > minsize:
                label += 1
                newbac[labeled_bacteria == region.label] = label
            if region.area > maxsize:
                stats["num_rejected_area"] += 1


#        if stats["num_rejected_area"]>0:
        segs2[ch_n] = newbac
    return segs2, thresh_array
Example #24
0
def blur_threshold_mask(bmap, threshold=None):
    if threshold is None:
        threshold = threshold_li(bmap)
    elif threshold < 0 or threshold > 1:
        raise ValueError('Threshold must be a real number between 0 and 1.')
    return bmap < threshold
Example #25
0
    greenimgs = sorted(glob.glob(filepath + "*Green -*"))
    blueimgs = sorted(glob.glob(filepath + "*Blue -*"))
    uvimgs = sorted(glob.glob(filepath + "*UV -*"))

    for i in np.arange(len(redimgs)):
        t1 = time.time()
        cellImagesRAW = []
        vacuoleArr = []
        print("Markers from", uvimgs[i], "Cells from", redimgs[i])

        r = io.imread(redimgs[i])
        g = io.imread(greenimgs[i])
        b = io.imread(blueimgs[i])
        u = io.imread(uvimgs[i])

        thresh = filters.threshold_li(u)
        mask = u <= thresh
        labeled = measure.label(mask, background=1)
        markers = rank.median(labeled, disk(25))

        p0, p1 = np.percentile(
            r, (10, 70)
        )  # These parameters can be changed to affect the sensitivity of measurement
        rRescaled = exposure.rescale_intensity(r, in_range=(p0, p1))
        thresh = filters.threshold_li(rRescaled)
        mask = rRescaled <= thresh
        gradient = rank.gradient(mask == 0, disk(2))

        labeled = segmentation.watershed(gradient, markers)
        labeled = segmentation.clear_border(labeled)  # Get rid of border cells
Example #26
0
def apply_li_threshold(image):
    return image > f.threshold_li(image)
Example #27
0
 file_suffix = '.npy'
 file_reading = os.path.join(
     sample_saving_path,
     file_name + image_name + channel_color + file_suffix)
 mm = np.load(file_reading)
 mmm = np.copy(mm)
 total_pixel_y, total_pixel_x = mmm.shape
 ### reading mmm_array ---
 ### filtering_noise_particle ---
 #from skimage import filters
 #from skimage.morphology import disk
 #mmm = filters.median(mmm)
 ### filtering_noise_particle +++
 ###
 from skimage.filters import threshold_otsu, threshold_yen, threshold_li, threshold_isodata
 aaa = threshold_li(mmm)
 bool_mmm = mmm > aaa
 ### boundary_masking +++
 bool_mmm[:, :2] = False
 bool_mmm[:, -2:] = False
 bool_mmm[:2, :] = False
 bool_mmm[-2:, :] = False
 ### boundary_masking ---
 from skimage.morphology import remove_small_objects
 bbb = remove_small_objects(bool_mmm, min_size=2)
 from skimage.morphology import skeletonize
 new_mmm = skeletonize(bbb)
 new_mmm = np.int64(new_mmm)  #converting bool into number(1, 0)
 ###
 file_suffix = '.png'
 saving_data_file = file_name + section_name_in
Example #28
0
def separate_watershed(
    vdf_temp,
    min_distance=1,
    min_size=1,
    max_size=np.inf,
    max_number_of_grains=np.inf,
    marker_radius=1,
    threshold=False,
    exclude_border=False,
    plot_on=False,
):
    """Separate segments from one VDF image using edge-detection by the
    sobel transform and the watershed segmentation implemented in
    scikit-image. See [1,2] for examples from scikit-image.

    Parameters
    ----------
    vdf_temp : np.array
        One VDF image.
    min_distance: int
        Minimum distance (in pixels) between markers for them to be
        considered separate markers for the watershed segmentation.
    min_size : float
        Grains with size (i.e. total number of pixels) below min_size
        are discarded.
    max_size : float
        Grains with size (i.e. total number of pixels) above max_size
        are discarded.
    max_number_of_grains : int
        Maximum number of grains included in the returned separated
        grains. If it is exceeded, those with highest peak intensities
        will be returned.
    marker_radius : float
        If 1 or larger, each marker for watershed is expanded to a disk
        of radius marker_radius. marker_radius should not exceed
        2*min_distance.
    threshold : bool
        If True, a mask is calculated by thresholding the VDF image by
        the Li threshold method in scikit-image. If False (default), the
        mask is the boolean VDF image.
    exclude_border : int or True, optional
        If non-zero integer, peaks within a distance of exclude_border
        from the boarder will be discarded. If True, peaks at or closer
        than min_distance of the boarder, will be discarded.
    plot_on : bool
        If True, the VDF, the mask, the distance transform
        and the separated grains will be plotted in one figure window.

    Returns
    -------
    sep : np.array
        Array containing segments from VDF images (i.e. separated
        grains). Shape: (image size x, image size y, number of grains)

    References
    ----------
    [1] http://scikit-image.org/docs/dev/auto_examples/segmentation/
        plot_watershed.html
    [2] http://scikit-image.org/docs/dev/auto_examples/xx_applications/
        plot_coins_segmentation.html#sphx-glr-auto-examples-xx-
        applications-plot-coins-segmentation-py
    """

    # Create a mask from the input VDF image.
    if threshold:
        th = threshold_li(vdf_temp)
        mask = np.zeros_like(vdf_temp)
        mask[vdf_temp > th] = True
    else:
        mask = vdf_temp.astype("bool")

    # Calculate the Eucledian distance from each point in the mask to the
    # nearest background point of value 0.
    distance = distance_transform_edt(mask)

    # If exclude_boarder is given, the edge of the distance is removed
    # by erosion. The distance image is used to find markers, and so the
    # erosion is done to avoid that markers are located at the edge
    # of the mask.
    if exclude_border > 0:
        distance_mask = binary_erosion(distance,
                                       structure=disk(exclude_border))
        distance = distance * distance_mask.astype("bool")

    # Find the coordinates of the local maxima of the distance transform.
    local_maxi = peak_local_max(
        distance,
        indices=False,
        min_distance=1,
        num_peaks=max_number_of_grains,
        exclude_border=exclude_border,
        threshold_rel=None,
    )
    maxi_coord1 = np.where(local_maxi)

    # Discard maxima that are found at pixels that are connected to a
    # smaller number of pixels than min_size. Used as markers, these would lead
    # to segments smaller than min_size and should therefore not be
    # considered when deciding which maxima to use as markers.
    if min_size > 1:
        labels_check = label(mask)[0]
        delete_indices = []
        for i in np.arange(np.shape(maxi_coord1)[1]):
            index = np.transpose(maxi_coord1)[i]
            label_value = labels_check[index[0], index[1]]
            if len(labels_check[labels_check == label_value]) < min_size:
                delete_indices.append(i)
                local_maxi[index[0], index[1]] = False
        maxi_coord1 = np.delete(maxi_coord1, delete_indices, axis=1)

    # Cluster the maxima by DBSCAN based on min_distance. For each
    # cluster, only the maximum closest to the average maxima position is
    # used as a marker.
    if min_distance > 1 and np.shape(maxi_coord1)[1] > 1:
        clusters = DBSCAN(
            eps=min_distance,
            metric="euclidean",
            min_samples=1,
        ).fit(np.transpose(maxi_coord1))
        local_maxi = np.zeros_like(local_maxi)
        for n in np.arange(clusters.labels_.max() + 1):
            maxi_coord1_n = np.transpose(maxi_coord1)[clusters.labels_ == n]
            com = np.average(maxi_coord1_n, axis=0).astype("int")
            index = distance_matrix([com], maxi_coord1_n).argmin()
            index = maxi_coord1_n[index]
            local_maxi[index[0], index[1]] = True

    # Use the resulting maxima as markers. Each marker should have a
    # unique label value. For each maximum, generate markers with the same
    # label value in a radius given by marker_radius centered at the
    # maximum position. This is done to make the segmentation more robust
    # to local changes in pixel values around the marker.
    markers = label(local_maxi)[0]
    if marker_radius >= 1:
        disk_mask = disk(marker_radius)
        for mm in np.arange(1, np.max(markers) + 1):
            im = np.zeros_like(markers)
            im[np.where(markers == mm)] = markers[np.where(markers == mm)]
            markers_temp = convolve2d(im,
                                      disk_mask,
                                      boundary="fill",
                                      mode="same",
                                      fillvalue=0)
            markers[np.where(markers_temp)] = mm
    markers = markers * mask

    # Find the edges of the VDF image using the Sobel transform.
    elevation = sobel(vdf_temp)

    # 'Flood' the elevation (i.e. edge) image from basins at the marker
    # positions. Find the locations where different basins meet, i.e.
    # the watershed lines (segment boundaries). Only search for segments
    # (labels) in the area defined by mask.
    labels = watershed(elevation, markers=markers, mask=mask)

    sep = np.zeros(
        (np.shape(vdf_temp)[0], np.shape(vdf_temp)[1], (np.max(labels))),
        dtype="int32")
    n, i = 1, 0
    while (np.max(labels)) > n - 1:
        sep_temp = labels * (labels == n) / n
        sep_temp = np.nan_to_num(sep_temp)
        # Discard a segment if it is too small or too large, or else add
        # it to the list of separated segments.
        if (np.sum(sep_temp, axis=(0, 1)) < min_size) or np.sum(
                sep_temp, axis=(0, 1)) > max_size:
            sep = np.delete(sep, ((n - i) - 1), axis=2)
            i = i + 1
        else:
            sep[:, :, (n - i) - 1] = sep_temp
        n = n + 1
    # Put the intensity from the input VDF image into each segmented area.
    vdf_sep = np.broadcast_to(vdf_temp.T, np.shape(sep.T)) * (sep.T == 1)

    if plot_on:  # pragma: no cover
        # If segments have been discarded, make new labels that do not
        # include the discarded segments.
        if np.max(labels) != (np.shape(sep)[2]) and (np.shape(sep)[2] != 0):
            labels = sep[:, :, 0]
            for i in range(1, np.shape(sep)[2]):
                labels = labels + sep[..., i] * (i + 1)
        # If no separated particles were found, set all elements in
        # labels to 0.
        elif np.shape(sep)[2] == 0:
            labels = np.zeros(np.shape(labels))

        seps_img_sum = np.zeros_like(vdf_temp).astype("float64")
        for lbl, vdf in zip(np.arange(1, np.max(labels) + 1), vdf_sep):
            mask_l = np.zeros_like(labels).astype("bool")
            _idx = np.where(labels == lbl)
            mask_l[_idx] = 1
            seps_img_sum += vdf_temp * mask_l / np.max(vdf_temp[_idx])
            seps_img_sum[_idx] += lbl

        maxi_coord = np.where(local_maxi)

        fig, axes = plt.subplots(2, 3, sharex=True, sharey=True)
        ax = axes.ravel()

        ax[0].imshow(vdf_temp, cmap=plt.cm.magma_r)
        ax[0].axis("off")
        ax[0].set_title("VDF")

        ax[1].imshow(mask, cmap=plt.cm.gray_r)
        ax[1].axis("off")
        ax[1].set_title("Mask")

        ax[2].imshow(distance, cmap=plt.cm.gray_r)
        ax[2].axis("off")
        ax[2].set_title("Distance and markers")
        ax[2].imshow(masked_where(markers == 0, markers),
                     cmap=plt.cm.gist_rainbow)
        ax[2].plot(maxi_coord1[1], maxi_coord1[0], "k+")
        ax[2].plot(maxi_coord[1], maxi_coord[0], "gx")

        ax[3].imshow(elevation, cmap=plt.cm.magma_r)
        ax[3].axis("off")
        ax[3].set_title("Elevation")

        ax[4].imshow(labels, cmap=plt.cm.gnuplot2_r)
        ax[4].axis("off")
        ax[4].set_title("Labels")

        ax[5].imshow(seps_img_sum, cmap=plt.cm.magma_r)
        ax[5].axis("off")
        ax[5].set_title("Segments")

    return vdf_sep
Example #29
0
        segments.append(collect_gs[y_low:y_high, :])  # contains white background, and have grayscale
        coords.append([y_low, y_high])
        # need to handle the end, i.e. after the last cut
print adjusted_cuts
"""for seg in segments:  # want to collect the histograms of each segment
    # Image.fromarray(seg).show()
    hist_seg = cv2.calcHist([seg], [0], None, [256], [0, 256])  # segment is gs on white background
    plt.plot(hist_seg)"""

# use some existing global thresholding method for each of the segments (different T for each segment)
# inputs should be grayscale (single channel)
black_bg = np.zeros((img.shape[0], img.shape[1]), dtype='uint8')

y_cur_min = 0
for seg in zip(segments, coords):  # is in order of increasing y-value
    threshglobal = filters.threshold_li(seg[0])  # Should be an integer? seg[0] refers to the first element, i.e. the segment and not the adjusted cut

    # compute adjustment to the threshold found above based on the ratio of foreground pixels to total pixels in segment
    # background_pixels
    background_pixels = np.where(seg[0] == 255)
    a = len(background_pixels[0])
    seg_img = seg[0]
    b = (seg_img.shape[0])*(seg_img.shape[1])

    adjustment_ratio = 1.0*a/b

    adjustment_value =  35*pow(adjustment_ratio, (1.0/2.0))  # gives a^b
    print "Adjustment: " + str(adjustment_value)
    threshglobal = threshglobal - adjustment_value
    # the larger the ratio, the larger the adjustment effect
Example #30
0
def threshcomp(Data):

    ###############################################################################
    #                        Determining Binary Values
    ###############################################################################

    binary_local = Data > threshold_local(Data, 3)
    binary_adaptive = Data > threshold_adaptive(Data, 3)
    binary_otsu = Data > threshold_otsu(Data)
    binary_yen = Data > threshold_yen(Data)
    binary_isodata = Data > threshold_isodata(Data)
    binary_li = Data > threshold_li(Data)
    binary_min = Data > threshold_minimum(Data)
    binary_mean = Data > threshold_mean(Data)
    binary_triangle = Data > threshold_triangle(Data)
    binary_niblack = Data > threshold_niblack(Data)
    binary_sauvola = Data > threshold_sauvola(Data)

    ###############################################################################
    #                                 Plots
    ###############################################################################

    fig, axes = plt.subplots(nrows=5, ncols=2, figsize=(12, 8))
    ax = axes.ravel()

    ax[0] = plt.subplot(6, 2, 1)
    ax[1] = plt.subplot(6, 2, 2)
    ax[2] = plt.subplot(6, 2, 3)
    ax[3] = plt.subplot(6, 2, 4)
    ax[4] = plt.subplot(6, 2, 5)
    ax[5] = plt.subplot(6, 2, 6)
    ax[6] = plt.subplot(6, 2, 7)
    ax[7] = plt.subplot(6, 2, 8)
    ax[8] = plt.subplot(6, 2, 9)
    ax[9] = plt.subplot(6, 2, 10)

    ax[0].imshow(Data, cmap=plt.cm.gray, aspect='auto')
    ax[0].set_title("Original")
    ax[0].set_ylim([200, 0])
    ax[0].set_xlim([100, 400])
    ax[0].axis('off')

    ax[1].imshow(binary_local, cmap=plt.cm.gray, aspect='auto')
    ax[1].set_title("Local")
    ax[1].set_ylim([200, 0])
    ax[1].set_xlim([100, 400])
    ax[1].axis('off')

    ax[2].imshow(binary_otsu, cmap=plt.cm.gray, aspect='auto')
    ax[2].set_title("Otsu")
    ax[2].set_ylim([200, 0])
    ax[2].set_xlim([100, 400])
    ax[2].axis('off')

    ax[3].imshow(binary_yen, cmap=plt.cm.gray, aspect='auto')
    ax[3].set_title("Yen")
    ax[3].set_ylim([200, 0])
    ax[3].set_xlim([100, 400])
    ax[3].axis('off')

    ax[4].imshow(binary_isodata, cmap=plt.cm.gray, aspect='auto')
    ax[4].set_title("Isodata")
    ax[4].set_ylim([200, 0])
    ax[4].set_xlim([100, 400])
    ax[4].axis('off')

    ax[5].imshow(binary_li, cmap=plt.cm.gray, aspect='auto')
    ax[5].set_title("Li")
    ax[5].set_ylim([200, 0])
    ax[5].set_xlim([100, 400])
    ax[5].axis('off')

    ax[6].imshow(binary_min, cmap=plt.cm.gray, aspect='auto')
    ax[6].set_title("Minimum")
    ax[6].set_ylim([200, 0])
    ax[6].set_xlim([100, 400])
    ax[6].axis('off')

    ax[7].imshow(binary_mean, cmap=plt.cm.gray, aspect='auto')
    ax[7].set_title("Mean")
    ax[7].set_ylim([200, 0])
    ax[7].set_xlim([100, 400])
    ax[7].axis('off')

    ax[8].imshow(binary_triangle, cmap=plt.cm.gray, aspect='auto')
    ax[8].set_title("Triangle")
    ax[8].set_ylim([200, 0])
    ax[8].set_xlim([100, 400])
    ax[8].axis('off')

    ax[9].imshow(binary_niblack, cmap=plt.cm.gray, aspect='auto')
    ax[9].set_title("Niblack")
    ax[9].set_ylim([200, 0])
    ax[9].set_xlim([100, 400])
    ax[9].axis('off')

    plt.savefig('thresh_comp.png')
    plt.show()
def test_acc(image_name):
    car_id = image_name.split('_')[0]
    angle_indicator = image_name.split('_')[1]
    nnet_model = joblib.load('nnet_20_10_5_2_adam_logistic_' +
                             angle_indicator + '.pkl')
    image = misc.imread('test_sample/' + image_name + '.jpg',
                        flatten=True).astype(float)
    image_rgb = misc.imread('test_sample/' + image_name + '.jpg')
    image_float = image_rgb.astype(float)
    image_mask_all_angles = misc.imread('train_all_masks/' + car_id + '.jpg',
                                        flatten=True) / 255.
    image_mask = misc.imread('train_masks/' + image_name + '_mask.gif',
                             flatten=True) / 255
    #io.imshow(image_mask)
    image_index = np.where(image >= 0)
    sobel = filters.sobel(image)  # working
    #io.imshow(sobel)
    sobel_blurred = filters.gaussian(sobel, sigma=1)  # Working
    #io.imshow(sobel_blurred)
    canny_filter_image = canny(image / 255.)
    #io.imshow(canny_filter_image)
    #    threshold_niblack_11 = filters.threshold_niblack(sobel_blurred,201)
    #io.imshow(threshold_niblack)
    threshold_li = filters.threshold_li(image)
    mask_li = image > threshold_li
    #io.imshow(mask)
    sobel_h = filters.sobel_h(image)
    sobel_v = filters.sobel_v(image)
    laplace = filters.laplace(image)
    threshold_local_51 = filters.threshold_local(image, 51)
    mask_local_51 = image > threshold_local_51
    #io.imshow(mask)
    df = pd.DataFrame()
    #    df['y'] = (image_index[0] - 639.5)/639.5
    #    df['x'] = (image_index[1] - 958.5)/958.5
    df['l1_dist_y'] = abs((image_index[0] - 639.5) / 639.5)
    df['l1_dist_x'] = abs((image_index[1] - 958.5) / 958.5)
    df['l2_dist'] = np.sqrt((df['l1_dist_x'])**2 +
                            (df['l1_dist_y'])**2) / np.sqrt(2)
    df['grey_values'] = image.reshape((1, 1918 * 1280))[0] / 255.
    df['red_values'] = image_rgb.reshape((3, 1918 * 1280))[0] / 255.
    df['blue_values'] = image_rgb.reshape((3, 1918 * 1280))[1] / 255.
    df['green_values'] = image_rgb.reshape((3, 1918 * 1280))[2] / 255.
    df['red_float'] = image_float.reshape((3, 1918 * 1280))[0] / 255.
    df['blue_float'] = image_float.reshape((3, 1918 * 1280))[1] / 255.
    df['green_float'] = image_float.reshape((3, 1918 * 1280))[2] / 255.
    df['sobel_blurred'] = sobel_blurred.reshape((1, 1918 * 1280))[0] / 255.
    df['canny_filter_image'] = canny_filter_image.reshape(
        (1, 1918 * 1280))[0].astype(int)
    df['sobel_h'] = sobel_h.reshape((1, 1918 * 1280))[0] / 255.
    df['sobel_v'] = sobel_v.reshape((1, 1918 * 1280))[0] / 255.
    df['laplace'] = laplace.reshape((1, 1918 * 1280))[0] / 511.
    df['threshold_local_51'] = mask_local_51.reshape(
        (1, 1918 * 1280))[0].astype(int)
    #    df['threshold_niblack_11'] = threshold_niblack_11.reshape((1,1918*1280))[0]#/255.
    df['threshold_li'] = mask_li.reshape((1, 1918 * 1280))[0].astype(int)
    df['mask'] = image_mask.reshape((1, 1918 * 1280))[0]
    df['mask'] = df['mask'].astype('category')
    df['pred_mask'] = nnet_model.predict(
        X=df[[col for col in df.columns if col != 'mask']])
    z = skm.confusion_matrix(df['mask'], df['pred_mask'])
    dice_coeff = 2 * (z[1][1]) / float(2 * z[1][1] + z[0][1] + z[1][0])
    print 'Dice Coefficient:', dice_coeff
    accuracy = 100 * (z[0][0] + z[1][1]) / float(sum(sum(z)))
    print 'Accuracy:', accuracy
    precision = 100 * (z[1][1]) / float(z[0][1] + z[1][1])
    print 'Precision:', precision
    recall = 100 * (z[1][1]) / float(z[1][0] + z[1][1])
    print 'Recall:', recall
    act_mask = np.array(df['mask'])
    act_mask = act_mask.reshape((1280, 1918))
    pred_mask = np.array(df['pred_mask']).astype(float)
    pred_mask = pred_mask.reshape((1280, 1918))
    return df, pred_mask, image, act_mask
Example #32
0
    kc = whiten(kc)
    outside = np.argwhere(np.sqrt(tx**2 + ty**2) > np.max(kx)).squeeze()
    kc[outside] = 0  # keep region of support same as radial
    kc = np.reshape(kc, (N, N, nc), order='F')

    # Make sure we gridded something recognizable
    ifft = lambda x0: np.fft.fftshift(np.fft.ifft2(
        np.fft.ifftshift(x0, axes=(0, 1)), axes=(0, 1)),
                                      axes=(0, 1))
    sos = lambda x0: np.sqrt(np.sum(np.abs(x0)**2, axis=-1))

    nx, ny = 1, 3
    plt.subplot(nx, ny, 1)
    true = sos(ifft(kc))
    true /= np.max(true.flatten())
    thresh = threshold_li(true)
    mask = convex_hull_image(true > thresh)
    true *= mask
    plt.imshow(true)
    plt.title('Cartesian Sampled')

    plt.subplot(nx, ny, 2)
    scgrog = sos(ifft(res))
    scgrog /= np.max(scgrog.flatten())
    scgrog *= mask
    plt.imshow(scgrog)
    plt.title('SC-GROG')

    plt.subplot(nx, ny, 3)
    plt.imshow(true - scgrog)
    plt.title('Residual')
Example #33
0
    csm = csm[:, :, sl, ..., 0].squeeze()
    # view(csm)
    print(im.shape, im.shape)

    # Adjust for coil sensitivities
    im0 = np.zeros((im.shape[:3]), dtype='complex')
    print(im0.shape)
    for ii in range(4):
        im0[..., ii] = np.sum(im[..., :, ii]*csm.conj(), axis=-1)

    # Now do GS recon
    TR = 6e-3
    M = gs_recon(im0, pc_axis=-1)
    m = int(M.shape[0]/4)
    M = M[m:-m, :]
    thresh = threshold_li(np.abs(M))
    mask = np.abs(M) > thresh
    df_est0 = mask*np.angle(M)
    # df_est = unwrap_phase(
    #     np.ma.array(df_est, mask=np.abs(mask - 1)))
    # df_est = np.unwrap(df_est, axis=0)*mask
    # df_est = np.unwrap(df_est, axis=1)*mask

    # win = np.hamming(M.shape[1])
    # win = np.outer(win, win)
    # df_est = np.fft.fft2(df_est)*win
    # df_est = np.fft.ifft2(df_est)
    df_est0 /= np.pi*TR
    # view(df_est0)
    # view(df_est/np.max(np.abs(df_est.flatten())))
Example #34
0
def walsh(imspace, mask=None, coil_axis=-1):
    '''Stochastic matched filter coil combine.

    Parameters
    ----------
    mask : array_like
        A mask indicating which pixels of the coil sensitivity mask
        should be computed. If ``None``, this will be computed by
        applying a threshold to the sum-of-squares coil combination.
        Must be the same shape as a single coil.
    coil_axis : int
        Dimension that has coils.

    Notes
    -----
    Adapted from [1]_.  Based on the paper [2]_.

    References
    ----------
    .. [1] https://github.com/ismrmrd/ismrmrd-python-tools/
           blob/master/ismrmrdtools/coils.py
    .. [2] Walsh, David O., Arthur F. Gmitro, and Michael W.
           Marcellin. "Adaptive reconstruction of phased array MR
           imagery." Magnetic Resonance in Medicine: An Official
           Journal of the International Society for Magnetic
           Resonance in Medicine 43.5 (2000): 682-690.
    '''
    imspace = np.moveaxis(imspace, coil_axis, -1)
    ncoils = imspace.shape[-1]
    ns = np.prod(imspace.shape[:-1])

    if mask is None:
        sos = np.sqrt(np.sum(np.abs(imspace)**2, axis=-1))
        thresh = threshold_li(sos)
        mask = (sos > thresh).flatten()
    else:
        mask = mask.flatten()
    assert mask.size == ns, 'mask must be the same size as a coil!'

    # Compute the sample auto-covariances pointwise, will be
    # Hermitian symmetric, only need lower triangular matrix
    Rs = np.empty((ncoils, ncoils, ns), dtype=imspace.dtype)
    for p in range(ncoils):
        for q in range(p):
            Rs[q,
               p, :] = (np.conj(imspace[..., p]) * imspace[..., q]).flatten()

    # TODO:
    # # Smooth the covariance
    # for p in range(ncoils):
    #     for q in range(ncoils):
    #         Rs[p, q] = smooth(Rs[p, q, ...], smoothing)

    # At each point in the image, find the dominant eigenvector
    # and corresponding eigenvalue of the signal covariance
    # matrix using the power method
    csm = np.zeros((ns, ncoils), dtype=imspace.dtype)
    for ii in np.nonzero(mask)[0]:
        R = Rs[..., ii]
        v = eigh(R, lower=False, eigvals=(ncoils - 1, ncoils - 1))[1].squeeze()
        csm[ii, :] = v / np.linalg.norm(v)

    return np.moveaxis(np.reshape(csm, imspace.shape), -1, coil_axis)
Example #35
0
    #plt.show()

    #image = data.imread("/Users/exequiel/projects/roots/python/processing/1.15.AVI/selected/frame-54.tiff")

    block_size = 35
    gray = rgb2gray(image)
    global_thresh = threshold_otsu(gray)
    print global_thresh
    global_thresh = 0.65
    for t in np.linspace(global_thresh,1.0,20):
        binary_global = gray > t
        #binary_global = gray > 0.90

        print "threshold_otsu",threshold_otsu(gray)
        print "threshold_isodata",threshold_isodata(gray)
        print "threshold_li",threshold_li(gray)
        print "threshold_yen",threshold_yen(gray)




        label_img = label(binary_global, connectivity=binary_global.ndim)
        props = regionprops(label_img)
        boxes = []
        for pp in props:
            minr, minc, maxr, maxc = pp.bbox
            boxes += [(minc, minr, maxc - minc, maxr - minr)]


        valid_boxes = filter_valid_boxes(boxes,6,40,14,24,300,900)
        if len(valid_boxes) > 0:
Example #36
0
def get_lines_and_without_lines_image(img, size=[100, 100]):
    #img = cv2.imread("Result/bank-0.png")
    #img = cv2.imread(img)
    #img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    #img = clahe.apply(img)
    img = cv2.bitwise_not(img)
    #element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))
    #img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, element)
    #img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, element)
    #th2 = cv2.adaptiveThreshold(img,255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,15,-2)
    #th2 = cv2.adaptiveThreshold(img,255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,35,-2)
    th2 = threshold_li(img)
    th2 = (img > th2) * 255
    th2 = img_as_ubyte(th2)
    kernel = np.ones((2, 7), np.uint8)
    th_v = cv2.dilate(th2, kernel, iterations=2)
    kernel = np.ones((2, 3), np.uint8)
    th_h = cv2.dilate(th2, kernel, iterations=1)

    horizontal = th2
    vertical = th2
    rows, cols = horizontal.shape
    horizontalsize = size[0]
    horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT,
                                                    (horizontalsize, 1))
    horizontal_skel = cv2.erode(th_h, horizontalStructure, (-1, -1))
    horizontal_skel = cv2.dilate(horizontal_skel, horizontalStructure,
                                 (-1, -1))
    horizontal_skel = image_skeleton(horizontal_skel, (2, 1))
    horizontal = cv2.erode(horizontal, horizontalStructure, (-1, -1))
    horizontal = cv2.dilate(horizontal, horizontalStructure, (-1, -1))
    horizontal_inv = cv2.bitwise_not(horizontal)
    masked_img = cv2.bitwise_and(img, img, mask=horizontal_inv)
    masked_img_inv = cv2.bitwise_not(masked_img)
    horizontal_mask = masked_img_inv
    #cv2.imwrite("horizontal.jpg", masked_img_inv)

    verticalsize = size[1]
    verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT,
                                                  (1, verticalsize))
    vertical_skel = cv2.erode(th_v, verticalStructure, (-1, -1))
    vertical_skel = cv2.dilate(vertical_skel, verticalStructure, (-1, -1))
    vertical_skel = image_skeleton(vertical_skel, (5, 1))
    vertical_skel = cv2.bitwise_not(vertical_skel)
    vertical = cv2.erode(vertical, verticalStructure, (-1, -1))
    vertical = cv2.dilate(vertical, verticalStructure, (-1, -1))
    vertical_inv = cv2.bitwise_not(vertical)
    masked_img = cv2.bitwise_and(img, img, mask=vertical_inv)
    masked_img_inv = cv2.bitwise_not(masked_img)
    vertical_mask = masked_img_inv
    #cv2.imwrite("vertical.jpg", masked_img_inv)

    final_without_lines = cv2.bitwise_or(horizontal_mask, vertical_mask)
    final_only_lines = cv2.bitwise_xor(horizontal_mask, vertical_mask)
    cv2.imwrite("final_without_lines.png", final_without_lines)
    cv2.imwrite("final_only_lines.png", final_only_lines)
    cv2.imwrite("final_only_lines_h.png", horizontal_skel)
    cv2.imwrite("final_only_lines_v.png", vertical_skel)
    #final_without_lines = cv2.bitwise_not(final_without_lines)
    #th2 = cv2.adaptiveThreshold(final_without_lines,255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,15,-2)
    ret, final_without_lines = cv2.threshold(final_without_lines, 127, 255, 0)
    #th2 = threshold_minimum(final_without_lines)
    #th2 = (img > th2)*255
    #th2 = img_as_ubyte(th2)
    #final_without_lines = cv2.bitwise_not(th2)

    kernel = np.ones((2, 2), np.uint8)
    final_without_lines = cv2.morphologyEx(final_without_lines,
                                           cv2.MORPH_CLOSE, kernel)
    cv2.imwrite("final_thresholded.png", final_without_lines)
    '''
    th2 = cv2.medianBlur(th2,7)
    th2_1 = cv2.bitwise_not(th2)
    verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 5))
    th2 = cv2.erode(th2_1, verticalStructure, (-1, -1), iterations=2)
    horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (5,1))
    th2 = cv2.erode(th2, horizontalStructure, (-1, -1), iterations=1)
    th2 = cv2.bitwise_not(th2)
    th2 = cv2.bitwise_or(th2_1,th2)
    #th2 = cv2.bitwise_xor(th2_1,th2)
    cv2.imwrite('threshold.png', th2)
    '''

    return horizontal_skel, vertical_skel, final_without_lines, th2
    def create_slicemap_config(self):
        filter = self.filter_name
        slicemaps_paths = []
        for i in range(0, self.slicemaps_number):
            slicemaps_paths.append(
                os.path.join(
                    self.relative_path_to_slicemaps_dir,
                    self.slicemap_name_format.format(
                        i,
                        self.row_col[0],
                        self.row_col[1],
                        int(self.slicemap_size[0]),
                        int(self.slicemap_size[1]),
                        self.filter_name,
                    ),
                )
            )

        rows_cols = self.row_col
        slicemap_size = self.slicemap_size
        slices_range = self.slices_range
        original_slice_size = self.original_slice_size
        volume_size = [
            self.area_of_slice[1][0] - self.area_of_slice[0][0],
            self.area_of_slice[1][1] - self.area_of_slice[0][1],
            self.slices_range[1] - self.slices_range[0],
        ]
        area_of_slice = [self.area_of_slice[0], self.area_of_slice[1]]

        slice_path_to_middle_slice = self.slices_path_list[int((self.slices_range[0] + self.slices_range[1]) / 2)]
        middle_slice = Image.open(slice_path_to_middle_slice)
        middle_slice_numpy_array = numpy.array(middle_slice)
        threshold_otsu_index = threshold_otsu(middle_slice_numpy_array) / 255.0
        threshold_isodata_index = threshold_isodata(middle_slice_numpy_array) / 255.0
        threshold_yen_index = threshold_yen(middle_slice_numpy_array) / 255.0
        threshold_li_index = threshold_li(middle_slice_numpy_array) / 255.0

        print("******************************************************************")
        print("Slicemap size:                   {0},{1} px".format(self.slicemap_size[0], self.slicemap_size[1]))
        print("Number of slicemaps:             {0}".format(self.slicemaps_number))
        print("Rows and cols:                   {0},{1}".format(rows_cols[0], rows_cols[1]))
        print("Number of slices:                {0}".format(self.number_of_slices))
        print(
            "Original slice size:             {0},{1} px".format(
                int(self.original_slice_size[0]), int(self.original_slice_size[1])
            )
        )
        print(
            "Slicemap slice size:             {0},{1} px".format(
                int(self.slicemap_slice_size[0]), int(self.slicemap_slice_size[1])
            )
        )
        print(
            "Proposional slicemap slice size: {0},{1} px".format(
                self.proposional_slicemap_slice_size[0], self.proposional_slicemap_slice_size[1]
            )
        )
        print("Volume proportions:              {0},{1},{2}".format(volume_size[0], volume_size[1], volume_size[2]))
        print("Interpolation filter name:       {0}".format(self.filter_name))
        print("Number of rows and cols:         {0},{1}".format(self.row_col[0], self.row_col[1]))
        print(
            "Global path to slicemaps:        {0}".format(
                os.path.join(
                    self.global_path_to_slicemaps_dir,
                    self.slicemap_name_format.format(
                        "n",
                        self.row_col[0],
                        self.row_col[1],
                        int(self.slicemap_size[0]),
                        int(self.slicemap_size[1]),
                        self.filter_name,
                    ),
                )
            )
        )
        print(
            "Relative path to slicemaps:      {0}".format(
                os.path.join(
                    self.relative_path_to_slicemaps_dir,
                    self.slicemap_name_format.format(
                        "n",
                        self.row_col[0],
                        self.row_col[1],
                        int(self.slicemap_size[0]),
                        int(self.slicemap_size[1]),
                        self.filter_name,
                    ),
                )
            )
        )
        print("Path to slices:                  {0}".format(self.path_to_slices))
        print("Name of fisrt slice:             {0}".format(self.files_list[0]))
        print(
            "Name of fisrt slicemaps:         {0}".format(
                self.slicemap_name_format.format(
                    0,
                    self.row_col[0],
                    self.row_col[1],
                    int(self.slicemap_size[0]),
                    int(self.slicemap_size[1]),
                    self.filter_name,
                )
            )
        )
        print("Area_of_slice:                   {0},{1} px".format(self.area_of_slice[0], self.area_of_slice[1]))
        print("threshold_otsu_index:            {0}".format(threshold_otsu_index))
        print("threshold_isodata_index:         {0}".format(threshold_isodata_index))
        print("threshold_yen_index:             {0}".format(threshold_yen_index))
        print("threshold_li_index:              {0}".format(threshold_li_index))

        data = {}
        data["filter"] = self.filter_name
        data["slicemaps_paths"] = []
        for i in range(0, self.slicemaps_number):
            data["slicemaps_paths"].append(
                os.path.join(
                    self.relative_path_to_slicemaps_dir,
                    self.slicemap_name_format.format(
                        i,
                        self.row_col[0],
                        self.row_col[1],
                        int(self.slicemap_size[0]),
                        int(self.slicemap_size[1]),
                        self.filter_name,
                    ),
                )
            )

        data["row_col"] = rows_cols
        data["slicemap_size"] = slicemap_size
        data["slices_range"] = slices_range
        data["original_slice_size"] = original_slice_size
        data["slicemap_slice_size"] = self.slicemap_slice_size
        data["volume_size"] = volume_size
        data["area_of_slice"] = area_of_slice
        data["threshold_indexes"] = {
            "otsu": threshold_otsu_index,
            "isodata": threshold_isodata_index,
            "yen": threshold_yen_index,
            "li": threshold_li_index,
        }

        jsonString = json.dumps(data)

        print("************ CONFIG BEGIN ************ ")
        print(jsonString)
        print("************ CONFIG END ************** ")

        if not (os.path.exists(self.path_to_configs_dir)):
            os.makedirs(self.path_to_configs_dir)

        config_file = open(self.path_to_config, "w")
        config_file.write(jsonString)
        config_file.close()
Example #38
0
plt.figure('thresh',figsize=(8,12))
plt.subplot(321)
plt.title('original image')
plt.imshow(image,plt.cm.gray)
plt.subplot(322)
plt.title('binary_otsu image')
thresh = filters.threshold_otsu(image)   #返回一个阈值
dst = (image <= thresh)*1.0              #根据阈值进行分割
plt.imshow(dst,plt.cm.gray)
plt.subplot(323)
plt.title('binary_yen image')
dst = (image <= filters.threshold_yen(image) )*1.0 
plt.imshow(dst,plt.cm.gray)
plt.subplot(324)
plt.title('binary_li image')
dst = (image <= filters.threshold_li(image) )*1.0 
plt.imshow(dst,plt.cm.gray)
'''2、基于isodata的阈值分割方法'''
plt.subplot(325)
plt.title('binary_isodata image')
dst = (image <= filters.threshold_isodata(image) )*1.0 
plt.imshow(dst,plt.cm.gray)
'''2、基于local的阈值分割方法'''
plt.subplot(326)
plt.title('binary_local image')
dst = filters.threshold_local(image, 15, method='gaussian') #返回一个阈值图像
plt.imshow(dst,plt.cm.gray)
plt.show()
# =============================================================================
print('''十、基本图形的绘制''')
# =============================================================================
Example #39
0
def processImage(captchaPath, report=None, backgroundLayerPath=None, canny_sigma=0.1, corner_min_dist=2, debug = False):
	"""
		Processes the given image and returns a number of feature points.
		These feature points are presumably corner points of the tetragon.
	"""
	image = io.imread(captchaPath, True);
	
	image_without_bg = None
	
# remove background, if available
	if not None == backgroundLayerPath:
		bgl = io.imread(backgroundLayerPath, True)
		image_without_bg = (image - bgl)
	else:
		image_without_bg = image

# applying threshold operators
	thresh = threshold_otsu(image_without_bg)
	thrs_image = image_without_bg > thresh

	thresh_li = threshold_li(image_without_bg)
	thrs_image_li = image_without_bg > thresh_li

	thresh_yen = threshold_yen(image_without_bg)
	thrs_image_yen = image_without_bg > thresh_yen

#	thrs_image = thrs_image * thrs_image_li * thrs_image_yen
	thrs_image = image_without_bg * thrs_image
	thrs_image = thrs_image * thrs_image_li
	thrs_image = thrs_image * thrs_image_yen

#	thrs_image = ndi.gaussian_filter(thrs_image, 0.8)
# take the gray image
	gray_result = rgb2gray(thrs_image)

# find edges
#	canny_result = feature.canny(gray_result, sigma=0.5, low_threshold=1.8)
	canny_result = gray_result 

# store image
	processedImageName = captchaPath[0:len(captchaPath)-4] + "_processed.png"
	io.imsave(processedImageName, canny_result.clip(-1, 1))
	if not None == report:
		report.setProcessedImage(processedImageName)

	coords = feature.corner_peaks(feature.corner_harris(canny_result), min_distance=corner_min_dist)

	if debug:
		fig, axes = plt.subplots(nrows=6, figsize=(8, 3))
		ax0, ax1, ax2, ax3, ax4, ax5 = axes

		ax0.imshow(image, cmap=plt.cm.gray)
		ax0.set_title('Original image')
		ax0.axis('off')

		ax1.imshow(image_without_bg, cmap=plt.cm.gray)
		ax1.set_title('Image without background')
		ax1.axis('off')

		ax2.imshow(thrs_image, cmap=plt.cm.gray)
		ax2.set_title('Thresholded image')
		ax2.axis('off')

		ax3.imshow(gray_result, cmap=plt.cm.gray)
		ax3.set_title('After RGB -> Gray')
		ax3.axis('off')

		ax4.imshow(canny_result, cmap=plt.cm.gray)
		ax4.set_title('After Canny')
		ax4.axis('off')

		ax5.imshow(canny_result, cmap=plt.cm.gray)
		ax5.plot(coords[:, 1], coords[:, 0], '+r', markersize=15)
		ax5.set_title('Detected Features')
		ax5.axis('off')

		plt.show()

	return coords
Example #40
0
def segmentation(image, method='otsu'):

    if (method == 'region'):
        sobel_image = filters.sobel(image)
        
        makers = sobel_image < sobel_image.max()*0.1
        makers = ndi.label(makers)[0]
    
        labels = watershed(sobel_image,makers) 
    
    elif (method == 'edge'):
        edges = canny(image,3)
        fill = ndi.binary_fill_holes(edges)
        labels = remove_small_objects(fill,10)
    
    elif (method == 'self_design'):
        width = 100;
        scale = 0.72;        
        [m, n] = image.shape
        thre = np.zeros((m,n))
        
        for i in range(0,n):
            ind_s = max(0,int(np.ceil(i-width/2)))
            ind_e = min(n-1,ind_s+width)
            current_image  = image[0:m-1, ind_s:ind_e]
            thre[0:m-1, i] = filters.threshold_otsu(current_image)*0.8
        labels = (image - thre) >=0    
    
    elif (method == 'thre_cons'):
        global_thre = image.max() * 0.3
        labels = image > global_thre

    elif (method == 'global_otsu'):
        global_thre = filters.threshold_otsu(image)
        labels = image > global_thre
    
    elif (method == 'local_otsu'):
        selem=disk(80)
        local_otsu = filters.rank.otsu(image, selem)
        labels = image > (np.true_divide(local_otsu,255))
    
    elif (method == 'yen'):
        global_thre = filters.threshold_yen(image)
        labels = image > (global_thre*2.5)
    
    elif (method == 'li'):
        global_thre = filters.threshold_li(image)
        labels = image > global_thre
    
    elif (method == 'isodata'):     
        global_thre = filters.threshold_isodata(image)
        labels = image > global_thre
    
    elif (method == 'adaptive'):
        block_size = 100
        image = np.true_divide(image,image.max()+np.spacing(1)) * 255
        labels = filters.threshold_adaptive(image, block_size, offset=10)

    elif (method == 'R_Walker'):
        data = image + 0.35 * np.random.randn(*image.shape)
        markers = np.zeros(data.shape, dtype=np.uint)
        markers[data < -0.3] = 1
        markers[data > 1.3] = 2
        labels = random_walker(data, markers, beta=10, mode='cg_mg')
    
    return labels
Example #41
0
> Import the appropriate thresholding and rgb2gray() functions.
> Turn the image to grayscale.
> Obtain the optimal thresh.
> Obtain the binary image by applying thresholding.
"""

import sys
from skimage.filters import try_all_threshold, threshold_li
from skimage.color import rgb2gray
from matplotlib import pyplot as plt
sys.path.append('./helpers')
from settings import nda_import_image, show_image

str_tools_image_path = './dataset/chapter 1/shapes52.jpg'
img_tools = nda_import_image(str_tools_image_path)


def apply_thresholding_test(img):
    img_grayscale = rgb2gray(img)
    fig, ax = try_all_threshold(img_grayscale, verbose=False)
    plt.show()


apply_thresholding_test(img_tools)

img_tools_grayscale = rgb2gray(img_tools)
li_thresh = threshold_li(img_tools_grayscale)
img_tools_binary = img_tools_grayscale > li_thresh
show_image(img_tools_binary)
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage as ndi
from skimage import morphology, color, data, filters, io, feature, exposure

img = io.imread('Image/011.png')

image = color.rgb2gray(img)
img_c = exposure.equalize_hist(image)

denoised = filters.rank.median(img_c, morphology.disk(5))  #过滤噪声
thresh = filters.threshold_li(denoised)

binary = denoised > thresh
for i in range(10):
    binary = morphology.binary_erosion(binary)

classes = ndi.label(binary)[0]
gradient = filters.rank.gradient(denoised, morphology.disk(5))
gradient_inv = gradient.max() - gradient
local_min = feature.peak_local_max(gradient_inv,
                                   indices=False,
                                   min_distance=35,
                                   num_peaks_per_label=1,
                                   labels=classes)
gradient_selected = np.ones(np.shape(image)) * gradient.max()
gradient_selected[local_min == True] = gradient[local_min == True]
markers = ndi.label(local_min)[0]
labels = morphology.watershed(gradient,
                              markers,
                              watershed_line=True,
def test_sample1():
    ROOT = os.path.abspath(os.path.dirname(__file__))
    filename = os.path.join(ROOT, "samples", "coins1.jpg")
    data = load_data(filename)
    data = sktrans.rescale(data, 0.1)
    plt.figure()
    plt.title("Original data")
    plt.imshow(data)
    plt.figure()
    filt = data[...,0].astype(float)#.mean(axis=-1)
    filt-=filt.min()
    filt/=filt.max()
    plt.imshow(filt, cmap='jet')
    plt.title("Red channel")

    edges = skfilt.sobel(skfilt.gaussian_filter(filt, 4.0))
    plt.figure()
    plt.title("Edges (Sobel)")
    plt.imshow(edges)

    markers = np.zeros(filt.shape, dtype=int)
    med = np.median(filt)
    mad = np.median(np.abs(filt - med))
    markers[filt <  med] = 1
    markers[filt >  (med + 3*mad)] = 2
    ws = skmo.watershed(edges, markers)
    plt.figure()
    plt.title("Watershed using edges")

    plt.imshow(filt, cmap='gray')
    plt.imshow(np.ma.masked_where(ws==0, ws), alpha=0.4)

    plt.figure()
    plt.imshow(skfilt.median(filt, np.ones((5,5), dtype=bool)))
    plt.title("Median filtered image")

    # Let's try scale space representation
    scales=np.arange(5, 40)
    if jmfilt:
        lg = jmfilt.scale_space_LoG(filt, scales=scales)
        med,mad = jmfilt.getMedMad(lg)
        bw = lg > (med + 3*mad)     # Automatic thresholding based on
                                    # median absolute deviation
        # Method 1
        ## Have to use maximum filter, one scale at a time?
        #maxim = np.zeros_like(lg)
        #for i,s in enumerate(scales):
        #    lgnow = np.zeros_like(lg)
        #    lgnow[...,i] = lg[...,i]
        #    lgmax = ndi.maximum_filter(lg, footprint=skmo.ball(s))
        #    maxim = np.maximum(lgmax, maxim)
        # Method 2
        # Find local maxima, then operate on peaks to suppress
        lgmax = ndi.maximum_filter(lg, size=3)
        peaks = np.array(((lgmax == lg)&bw).nonzero()).T
        peak_ints = lg[peaks.T.tolist()]
        # Now sort the peaks by the intensities
        order = np.argsort(peak_ints)[::-1]
        peak_ints = peak_ints[order]
        peaks = peaks[order]
        # Now suppress
        active = np.ones(peaks.shape[0], dtype=bool)
        for i, p in enumerate(peaks):
            if not active[i]:
                continue
            # Silence any nearby peaks
            dists = np.sqrt(np.sum( (peaks[:,:2]-p[:2])**2, axis=-1))
            nearby = dists < (2*scales[p[2]])
            nearby[i] = False   # Ignore self
            active[nearby] = False
        suppressed = peaks[~active]
        peaks = peaks[active]
        print("Peaks after non-maximal suppression:", len(peaks))
        plt.imshow(filt, cmap='gray')
        #plt.scatter(peaks[:,1], peaks[:,0], s=10*np.array(peaks[:,2]),
        #    marker='o', color="y", facecolor="none")
        #plt.scatter(suppressed[:,1], suppressed[:,0],
        #    s=10*np.array(suppressed[:,2]),
        #    marker='o', color="r", facecolor="none")
        # Add circles instead to get proper sizes
        ax = plt.gca()
        for p in peaks:
            c = plt.Circle(p[[1,0]], scales[p[2]], color='y', fill=False)
            ax.add_artist(c)
        for p in suppressed:
            c = plt.Circle(p[[1,0]], scales[p[2]], color='r', fill=False)
            ax.add_artist(c)

        plt.title("Scale space peaks")

    # Lastly, good old Hough
    bw_edges = edges > skfilt.threshold_li(edges)
    bw_edges = skmo.skeletonize(bw_edges)
    bw_edges = skmo.binary_dilation(bw_edges)
    hough_radii = scales
    hough_res = sktrans.hough_circle(bw_edges, hough_radii)

    centers = []
    accums = []
    radii = []
    for radius, h in zip(hough_radii, hough_res):
        num_peaks = 20
        peaks = skfeat.peak_local_max(h, num_peaks=num_peaks)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius] * num_peaks)

    # Draw the most prominent 5 circles
    image = skcolor.gray2rgb(filt)
    print(image.shape)
    for idx in np.argsort(accums)[::-1][:20]:
        center_x, center_y = centers[idx]
        radius = radii[idx]
        cx, cy = skdraw.circle_perimeter(center_y, center_x, radius)
        image[cy, cx] = (220, 20, 20)
    plt.figure()
    plt.imshow(filt, cmap='gray')
    plt.imshow(np.ma.masked_where(bw_edges==0, bw_edges), cmap='hsv',
        alpha=0.4)
    plt.title("Binary edges (input to hough)")
    plt.figure()
    plt.imshow(image)
    plt.title("Hough circle transform results")

    plt.show()

    return
    labels = process_file(filename)
    show_results(filename, labels)
    plt.show()
Example #44
0
# run dilation reconstruction on image. This contains the background.
dilated = reconstruction(seed, mask, method='dilation')



# subtract the dilated background image from the image
subtracted = image - dilated


# init disk kernel for dialtion
selem = disk(3)
# dilate the subtracted image
dilated = dilation(subtracted, selem)

# perform threshold on the image using triangle
thresh = threshold_li(dilated)
binary = dilated > thresh

# label discrete objects and assign each labeled area a number.
label_image = label(binary)
# remove small (artifactual) objects from the image
label_image = remove_small_objects(label_image, 300)

# init disk kernel for dilationg to get neuropils
kernel = disk(45)

# perform dilation on the image to get the neuron and the surrounding neuropil
neuropils = dilation(label_image, kernel)
# subtract neuron from dilation to get just the neuron
neuropils = neuropils - label_image
Example #45
0
def experiment_thresholding(votes_min=3):
    from skimage.filters import threshold_otsu
    from skimage.filters import threshold_li
    from skimage.filters import threshold_yen
    from skimage.filters import threshold_adaptive
    from scipy.ndimage import median_filter

    images = image_generator()

    for fn, im in images:
        print("inspecting image: ", fn)
        print("computing otsu threshold")
        otsu = threshold_otsu(im)
        otsu_ch1 = np.zeros(im.shape)
        otsu_ch2 = np.zeros(im.shape)
        otsu_ch3 = np.zeros(im.shape)
        otsu_ch1[im[:, :, 0] > otsu, 0] = 255
        otsu_ch2[im[:, :, 1] > otsu, 1] = 255
        otsu_ch3[im[:, :, 2] > otsu, 2] = 255
        otsu_ch1 = smallest_partition(otsu_ch1, 0)
        otsu_ch2 = smallest_partition(otsu_ch2, 1)
        otsu_ch3 = smallest_partition(otsu_ch3, 2)

        print("computing yen threshold")
        yen = threshold_yen(im)
        yen_ch1 = np.zeros(im.shape)
        yen_ch2 = np.zeros(im.shape)
        yen_ch3 = np.zeros(im.shape)
        yen_ch1[im[:, :, 0] > yen, 0] = 255
        yen_ch2[im[:, :, 1] > yen, 1] = 255
        yen_ch3[im[:, :, 2] > yen, 2] = 255
        yen_ch1 = smallest_partition(yen_ch1, 0)
        yen_ch2 = smallest_partition(yen_ch2, 1)
        yen_ch3 = smallest_partition(yen_ch3, 2)

        print("computing li threshold")
        li = threshold_li(im)
        li_ch1 = np.zeros(im.shape)
        li_ch2 = np.zeros(im.shape)
        li_ch3 = np.zeros(im.shape)
        li_ch1[im[:, :, 0] > li, 0] = 255
        li_ch2[im[:, :, 1] > li, 1] = 255
        li_ch3[im[:, :, 2] > li, 2] = 255
        li_ch1 = smallest_partition(li_ch1, 0)
        li_ch2 = smallest_partition(li_ch2, 1)
        li_ch3 = smallest_partition(li_ch3, 2)

        print("computing average threshold")
        av_ch1 = np.zeros(im.shape)
        av_ch2 = np.zeros(im.shape)
        av_ch3 = np.zeros(im.shape)
        votes1 = otsu_ch1 + yen_ch1 + li_ch1
        votes1 = otsu_ch1 + yen_ch1 + li_ch1
        votes2 = otsu_ch2 + yen_ch2 + li_ch2
        votes3 = otsu_ch3 + yen_ch3 + li_ch3
        av_ch1[votes1[:, :, 0] >= (255 * votes_min), 0] = 255
        av_ch2[votes2[:, :, 1] >= (255 * votes_min), 1] = 255
        av_ch3[votes3[:, :, 2] >= (255 * votes_min), 2] = 255

        thresholded_images = [
            otsu_ch1,
            otsu_ch2,
            otsu_ch3,
            yen_ch1,
            yen_ch2,
            yen_ch3,
            li_ch1,
            li_ch2,
            li_ch3,
            av_ch1,
            av_ch2,
            av_ch3,
        ]

        print("filtering out specks")
        for idx, im in enumerate(thresholded_images):
            thresholded_images[idx] = median_filter(im, size=3)

        titles = [
            "Channel 1 Otsu",
            "Channel 2 Otsu",
            "Channel 3 Otsu",
            "Channel 1 Yen",
            "Channel 2 Yen",
            "Channel 3 Yen",
            "Channel 1 Li",
            "Channel 2 Li",
            "Channel 3 Li",
            "Channel 1 Avg",
            "Channel 2 Avg",
            "Channel 3 Avg",
        ]

        print("plotting")
        plot_images(thresholded_images, titles=titles, suptitle=fn.split("/")[-1])
Example #46
0
ax[1].imshow(camera > optimal_camera_threshold, cmap='gray')
ax[1].set_title('thresholded')
ax[1].set_axis_off()

ax[2].plot(thresholds, entropies)
ax[2].set_xlabel('thresholds')
ax[2].set_ylabel('cross-entropy')
ax[2].vlines(optimal_camera_threshold,
             ymin=np.min(entropies) - 0.05 * np.ptp(entropies),
             ymax=np.max(entropies) - 0.05 * np.ptp(entropies))
ax[2].set_title('optimal threshold')

fig.tight_layout()

print('The brute force optimal threshold is:', optimal_camera_threshold)
print('The computed optimal threshold is:', filters.threshold_li(camera))

plt.show()

###############################################################################
# Next, let's use the ``iter_callback`` feature of ``threshold_li`` to examine
# the optimization process as it happens.

iter_thresholds = []

optimal_threshold = filters.threshold_li(camera,
                                         iter_callback=iter_thresholds.append)
iter_entropies = [_cross_entropy(camera, t) for t in iter_thresholds]

print('Only', len(iter_thresholds), 'thresholds examined.')
Example #47
0
		c = center[1] + radius*np.cos(rads)
		r = center[0] + radius*np.sin(rads)
	
		return np.array([c, r]).T

"""# Optimization in unsupervised segmentation:"""

text = data.page()
image_show(text)

text_threshold = filters.threshold_otsu(text) 

image_show(text > text_threshold);

text_threshold = filters.threshold_li(text)

image_show(text > text_threshold);

text_threshold = filters.threshold_local(text,block_size=51, offset=10) 
image_show(text > text_threshold);

"""# Optimization in snake based contour segmentation:"""

points = generate_circle(200, [160, 120], 60)[:-1]
fig, ax = image_show(image_gray)
ax.plot(points[:, 0], points[:, 1], '--r', lw=3)

"""**Generating snake based on circle:**"""

import skimage.segmentation as seg
Example #48
0
matplotlib.rcParams['font.size'] = 9
img_orig = '/home/andrea/Desktop/20160713_NCP_GO_Talos_121.jpg'
img_lowpass = '******'
out_dir = '/home/andrea/Desktop/test'
if not os.path.isdir(out_dir):
    os.makedirs(out_dir)
os.chdir(out_dir)
# print('Processing original')
# image_orig = imread(img_orig, as_grey=True, flatten = True)
# thresh_orig = threshold_isodata(image_orig)
# binary_orig = image_orig > thresh_orig
print('Processing lowpass isodata')
image = imread(img_lowpass, as_grey=True, flatten = True)
thresh_isodata = threshold_isodata(image)
thresh_otsu = threshold_otsu(image)
thresh_li = threshold_li(image)
thresh_yen = threshold_yen(image)
thresh_adaptive = threshold_adaptive(image, 3)
binary_isodata = image > thresh_isodata
binary_otsu = image > thresh_otsu
binary_li = image > thresh_li
binary_adaptive = image > thresh_adaptive
binary_yen = image > thresh_yen
# edges = canny(image_orig/255.)
# fill_image = ndi.binary_fill_holes(edges)
imshow(binary_isodata)
imshow(binary_otsu)
imshow(binary_yen)
imshow(binary_li)
imshow(binary_adaptive)