コード例 #1
0
def compareGreys(greyimage_before,
                 greyimage_after,
                 high_percentile=10,
                 mid_percentile=20):

    assert greyimage_before.shape == greyimage_after.shape

    # get some edges
    edge_roberts_before = roberts(greyimage_before)
    edge_roberts_after = roberts(greyimage_after)

    # pca on the edge arrays
    delta = np.dstack(
        [edge_roberts_after.ravel(),
         edge_roberts_before.ravel()])[0]
    pca = decomposition.PCA(n_components=2, whiten=False)
    pca.fit(delta)
    XY = pca.transform(delta)[:, 1].reshape(greyimage_before.shape)

    # set areas below given percentile thresholds
    midperc = np.percentile(XY, mid_percentile)
    highperc = np.percentile(XY, high_percentile)

    out = np.zeros((XY.shape), dtype=np.uint8)

    out[np.where(XY <= midperc)] = 1
    out[np.where(XY <= highperc)] = 2

    return out
コード例 #2
0
def colorize(im, with_edge):
    B, G, R = split_im(im)

    if with_edge:
        B_edge = roberts(B)
        G_edge = roberts(G)
        R_edge = roberts(R)
    else:
        B_edge = B
        G_edge = G
        R_edge = R

    im_height = B.shape[0]
    im_weight = B.shape[1]

    if max(im_height, im_weight) <= 500:
        G_displacement, _ = L2norm_optimization([-15, 15], B_edge, G_edge)
        R_displacement, _ = L2norm_optimization([-15, 15], B_edge, R_edge)
    else:
        G_displacement, _ = pyramid_processing(B_edge, G_edge)
        R_displacement, _ = pyramid_processing(B_edge, R_edge)

    G_aligned = shift_im(G, G_displacement[0], G_displacement[1])
    R_aligned = shift_im(R, R_displacement[0], R_displacement[1])

    im_stacked = stack_channel(B, G_aligned, R_aligned)
    displacement = [G_displacement, R_displacement]
    return im_stacked, displacement
コード例 #3
0
def skeleton_image(file):
    image_origin = io.imread(file, as_grey=True)

    image_origin = np.where(image_origin > 0, 1, 0)
    image_origin = adjunction_image(image_origin)
    # 骨架
    edge_roberts = roberts(image_origin)
    edge_roberts = feature.canny(image_origin, sigma = 1)
    edge_roberts = np.where(edge_roberts > 0, 3, 0)
    skeleton = skeletonize_3d(image_origin)
    # back_image = np.where(image_origin > 0, 0, 1)
    back_image = np.where(image_origin > 0, 0, 1)
    back_thin_images = skeletonize(back_image)
    [row, col] = back_thin_images.shape
    back_thin_image = np.zeros((row, col))
    back_thin_image[:, int(col / 5):int(col / 5) * 4] = back_thin_images[:, int(col / 5):int(col / 5) * 4]
    p2 = plt.subplot(421)
    p2.imshow(image_origin + back_thin_images, cmap="gray")

    total_image = edge_roberts + back_thin_images
    p2 = plt.subplot(422)
    p2.imshow(total_image)


    p3 = plt.subplot(425)
    p3.imshow(np.where(roberts(image_origin) > 0, 1, 0))
    p3 = plt.subplot(426)
    p3.imshow(np.where(sobel(image_origin) > 0, 2, 0))
    p3 = plt.subplot(427)
    p3.imshow(np.where(scharr(image_origin) > 0, 2, 0))
    p3 = plt.subplot(428)
    p3.imshow(np.where(prewitt(image_origin) > 0, 2, 0))

    plt.show()
コード例 #4
0
def pyramid_method(A, B):
    cropped_A = A[800:-800, 800:-800]
    cropped_B = B[800:-800, 800:-800]

    edge_A = roberts(cropped_A)
    edge_B = roberts(cropped_B)

    return pyramid_align(edge_A, edge_B, 1)
コード例 #5
0
ファイル: tools.py プロジェクト: mjirik/lisa
def roberts(data, sliceId=2):
    edges = np.zeros(data.shape)
    if sliceId == 2:
        for idx in range(data.shape[2]):
            edges[:, :, idx] = skifil.roberts(data[:, :, idx])
    elif sliceId == 0:
        for idx in range(data.shape[0]):
            edges[idx, :, :] = skifil.roberts(data[idx, :, :])
    return edges
コード例 #6
0
ファイル: tools.py プロジェクト: mjirik/lisa
def roberts(data, sliceId=2):
    edges = np.zeros(data.shape)
    if sliceId == 2:
        for idx in range(data.shape[2]):
            edges[:, :, idx] = skifil.roberts(data[:, :, idx])
    elif sliceId == 0:
        for idx in range(data.shape[0]):
            edges[idx, :, :] = skifil.roberts(data[idx, :, :])
    return edges
コード例 #7
0
ファイル: zad4lab2.py プロジェクト: 3elk4/Image-Processing
def highpass_filter(image, what):
    newImage = np.array(image)
    if newImage.ndim == 3:
        Filters = {
            'roberts': [
                filters.roberts(image[:, :, 0]),
                filters.roberts(image[:, :, 1]),
                filters.roberts(image[:, :, 2])
            ],
            'sobel': [
                filters.sobel(image[:, :, 0]),
                filters.sobel(image[:, :, 1]),
                filters.sobel(image[:, :, 2])
            ],
            'scharr': [
                filters.scharr(image[:, :, 0]),
                filters.scharr(image[:, :, 1]),
                filters.scharr(image[:, :, 2])
            ],
            'prewitt': [
                filters.prewitt(image[:, :, 0]),
                filters.prewitt(image[:, :, 1]),
                filters.prewitt(image[:, :, 2])
            ],
            'laplace': [
                filters.laplace(image[:, :, 0]),
                filters.laplace(image[:, :, 1]),
                filters.laplace(image[:, :, 2])
            ],
            'canny': [
                feature.canny(image[:, :, 0]),
                feature.canny(image[:, :, 1]),
                feature.canny(image[:, :, 2])
            ]
        }
        newImageR = Filters[what][0]
        newImageG = Filters[what][1]
        newImageB = Filters[what][2]

        newImage = np.array(newImageR + newImageG + newImageB)
    else:
        Filters = {
            'roberts': filters.roberts(image),
            'sobel': filters.sobel(image),
            'scharr': filters.scharr(image),
            'prewitt': filters.prewitt(image),
            'laplace': filters.laplace(image),
            'canny': feature.canny(image)
        }
        newImage = Filters[what]

    return np.clip(newImage, 0, 255)
コード例 #8
0
ファイル: sandbox.py プロジェクト: footh/dl
def edge_ops(file='zones/0.png', use_t=False):
    from skimage.filters import roberts, sobel, scharr, prewitt

    img = None
    if use_t:
        img = threshold(file)
    else:
        img = misc.imread(file)

    edge_roberts = roberts(img)
    edge_sobel = sobel(img)

    fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(8, 4))

    ax[0].imshow(edge_roberts, cmap=plt.cm.gray)
    ax[0].set_title('Roberts Edge Detection')

    ax[1].imshow(edge_sobel, cmap=plt.cm.gray)
    ax[1].set_title('Sobel Edge Detection')

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

    plt.tight_layout()
    plt.show()
コード例 #9
0
def roberts_filter(
    folder
):  # iterate through folders, assembling feature, label, and classname data objects
    class_id = 0
    features = []
    labels = np.array([])
    classnames = []
    for root, dirs, filenames in os.walk(folder):
        for d in sorted(dirs):
            #print("Reading data from", d)
            classnames.append(
                d)  # use the folder name as the class name for this label
            files = os.listdir(os.path.join(root, d))
            for f in files:
                imgFile = os.path.join(root, d, f)  # Load the image file
                img = plt.imread(imgFile)
                img = cv2.resize(
                    img,
                    (128,
                     128))  # Resizing all the images to insure proper reading
                img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                roberts_filt = roberts(img)

                features.append(roberts_filt.ravel())
                labels = np.append(
                    labels, class_id)  # Add it to the numpy array of labels
            class_id += 1

    features = np.array(
        features)  # Convert the list of features into a numpy array
    return features, labels, classnames
コード例 #10
0
def post_process_07(img, p):

    y, x = int(np.ceil(p[0])), int(np.ceil(p[1]))
    right = 16
    left = 16
    step = 2
    h = 15
    l = 10
    # yl, xl = pt[0] - (y-left) - 5, pt[1] - (x-h) - 5
    yp, xp = p[0] - (y - left) - 5, p[1] - (x - h) - 5
    arr1 = np.asarray(medfilt(img[x - h:x + l, y - left:y + right], 7),
                      np.uint8)
    edge_roberts = roberts(arr1)
    edge_sobel = sobel(arr1)
    edge_canny = cv2.Canny(arr1, 50, 100, apertureSize=3)
    cond = edge_sobel

    cond = np.asarray(cond > np.percentile(cond, 88), dtype=np.uint8)
    try:
        cond, ar = largest_object_and_skeleton(cond[5:-5, 5:-5])
    except:
        cond, ar = cond[5:-5, 5:-5], 0
    cond = np.asarray(cond, dtype=np.uint8)
    sc, sr = print_grad_right(cond)

    delta_col = sc - yp
    delta_row = sr - xp
    dg = np.sqrt(delta_col**2 + delta_row**2)
    if dg > 6:
        sc, sr = find_nearest_right(cond, yp, xp)
    delta_col = sc - yp
    delta_row = sr - xp
    return p[0] + delta_col, p[1] + delta_row
コード例 #11
0
def post_process_01(img, p):
    y, x = int(np.ceil(p[0])), int(np.ceil(p[1]))
    right = 10
    left = 16
    step = 2
    h = 15
    l = 10
    # yl, xl = pt[0] - (y-left) - 5, pt[1] - (x-h) - 5
    yp, xp = p[0] - (y - left) - 5, p[1] - (x - h) - 5
    arr1 = np.asarray(medfilt(img[x - h:x + l, y - left:y + right], 7),
                      np.uint8)
    edge_roberts = roberts(arr1)
    edge_sobel = sobel(arr1)
    edge_canny = cv2.Canny(arr1, 50, 100, apertureSize=3)
    cond = edge_sobel

    cond = np.asarray(cond > np.percentile(cond, 88), dtype=np.uint8)
    try:
        cond, ar = largest_object_and_skeleton(cond[5:-5, 5:-5])
    except:
        cond, ar = cond[5:-5, 5:-5], 0
    #     print("area", ar)
    cond = np.asarray(cond, dtype=np.uint8)
    pxs, pys = np.where(cond > 0)
    para_a = np.polyfit(pxs, pys, 2)[0]
    sc, sr = yp, xp
    if para_a >= 0:
        sc = np.where(np.sum(cond, axis=0) > 0)[0][0]
        sr = np.where(cond[:, sc] > 0)[0][0]
    delta_col = sc - yp
    delta_row = sr - xp
    #     print(delta_col, delta_row)
    yr, xr = p[0] + delta_col / 2, p[1] + delta_row / 2
    return yr, xr
コード例 #12
0
def segmentation(file_name):
    data_x, data_y, data_z = get_data(file_name)
    shape_x = len(np.unique(data_x))
    shape_y = len(np.unique(data_y))
    X = data_x.reshape(shape_x, shape_y)
    Y = data_y.reshape(shape_x, shape_y)
    Z = data_z.reshape(shape_x, shape_y)

    markers = np.zeros_like(Z)
    markers[Z < 0.15] = 1
    markers[Z > 0.3] = 2
    elevation_map = roberts(Z)
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3), sharex=True, sharey=True)
    # ax.imshow(Z)
    # ax.imshow(elevation_map, cmap=plt.cm.jet, interpolation='nearest')
    segmentation = watershed(elevation_map, markers)
    ax2.imshow(segmentation, interpolation='nearest')
    # ax.axis('off')
    # ax.set_title('segmentation')
    segmentation = ndi.binary_fill_holes(segmentation - 1)
    labeled_coins, _ = ndi.label(segmentation)
    ax1.imshow(Z, cmap=plt.cm.gray, interpolation='nearest')
    ax1.contour(segmentation, [0.5], linewidths=1.2, colors='y')
    ax1.axis('off')
    ax1.set_adjustable('box-forced')

    plt.show()
コード例 #13
0
def segm_2d(image, spacing=1.0):
    """This funtion segments the lungs from the given 2D slice."""
    # Step 1: Convert into a binary image.
    binary = image < -400
    # Step 2: Remove the blobs connected to the border of the image.
    cleared = segmentation.clear_border(binary)
    # Step 3: Label the image.
    label_image = measure.label(cleared)
    # Step 4: Keep the labels with 2 largest areas.
    areas = [r.area for r in measure.regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in measure.regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:                
                       label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    # Step 5: Erosion operation with a disk of radius 2. This operation is 
    #         seperating the lung nodules attached to the blood vessels.
    selem = morphology.disk(2.0 / spacing)
    binary = morphology.binary_erosion(binary, selem)
    # Step 6: Closure operation with a disk of radius 10. This operation is 
    #         to keep nodules attached to the lung wall.
    selem = morphology.disk(10.0 / spacing)
    binary = morphology.binary_closing(binary, selem)
    # Step 7: Fill in the small holes inside the binary mask of lungs.
    edges = filters.roberts(binary)
    binary = ndimage.binary_fill_holes(edges)

    return binary
コード例 #14
0
def getEdge(img, mode=0):
    return {
        0: sobel(img),
        1: scharr(img),
        2: prewitt(img),
        3: roberts(img)
    }.get(mode, sobel(img))
コード例 #15
0
    def get_mask(self, ImageId):

        img_masks = self.masks.loc[self.masks['ImageId'] == ImageId,
                                   'EncodedPixels'].tolist()
        # Take the individual ship masks and create a single mask array for all ships
        all_masks = np.zeros((self.img_size, self.img_size))
        all_edges = np.zeros((self.img_size, self.img_size))
        if img_masks == [-1]:
            return all_masks, all_edges
        for mask in img_masks:
            decode_mask = util.rle_decode(mask)

            if self.img_size != 768:
                decode_mask = cv2.resize(decode_mask,
                                         (self.img_size, self.img_size))
                decode_mask = (decode_mask > 0.5).astype(np.float32)
            all_masks += decode_mask

            edge = filters.roberts(decode_mask)
            #edge = np.where(edge > 0, 1.0, 0.0)
            all_edges += edge

        all_edges = np.where(all_edges > 0, 1.0, 0.0)

        #print(all_masks)
        return all_masks.astype(np.float32), all_edges.astype(np.float32)
コード例 #16
0
ファイル: snakes.py プロジェクト: mazoku/thesis
def calc_potential(img, params):
    c = 5
    # img_g = skifil.gaussian_filter(img, params['sigma'])
    img_g = skires.denoise_tv_chambolle(img, weight=params['tv_weight'])
    # img_g = skifil.denoise_bilateral(img, sigma_range=params['sigma_range'], sigma_spatial=params['sigma_spatial'])

    grad_1 = skifil.prewitt(img_g)
    grad_2 = skifil.roberts(img_g)
    grad_3 = skifil.scharr(img_g)
    grad_4 = skifil.sobel(img_g)

    # plt.figure()
    # hist, bins = skiexp.histogram(img_g)
    # plt.plot(bins, hist)
    # plt.show()

    pot = c * np.abs(grad_1)

    plt.figure()
    max_v = 0.0005
    plt.subplot(221), plt.imshow(grad_1, 'gray',
                                 interpolation='nearest'), plt.title('grad')
    plt.subplot(222), plt.imshow(grad_2,
                                 'gray',
                                 interpolation='nearest',
                                 vmax=max_v), plt.title('grad, adjusted vmax')
    plt.subplot(224), plt.imshow(
        pot, 'gray', interpolation='nearest'), plt.title('potential')
    # plt.show()

    return img_g
コード例 #17
0
def extract_object_for_single_image(im, save_dir, refer_index, name_list):
    #im: rgb image
    #refer_index: integer, used to name the extracted objects

    im_grey = color.rgb2grey(im)
    edges = filters.roberts(im_grey)
    pix_row_sum = [sum(row) for row in edges]

    condition = 3
    index = [i for i, x in enumerate(pix_row_sum) if x < condition]

    if index[0] == 0:
        status = 'wait'
    else:
        status = 'Ready for cut'
        start_point = 0

    for i in index[1:-1]:
        if status == 'Ready for cut':
            img = im[start_point:i, :, :]
            io.imsave(save_dir + 'cp' + str(refer_index) + '.jpg', img)
            name_list.append('cp' + str(refer_index) + '.jpg')
            refer_index += 1
            status = 'wait'
            start_point = i
        elif pix_row_sum[i + 1] >= condition:
            status = 'Ready for cut'
            start_point = i

    return refer_index
コード例 #18
0
def get_segmented_lungs(im):
    # Step 1: Convert into a binary image.
    binary = im < -400
    # Step 2: Remove the blobs connected to the border of the image.
    cleared = clear_border(binary)
    # Step 3: Label the image.
    label_image = label(cleared)
    # Step 4: Keep the labels with 2 largest areas.
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                    label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    # Step 5: Erosion operation with a disk of radius 2.
    # This operation is seperate the lung nodules attached to the blood vessels.
    selem = disk(2)
    binary = binary_erosion(binary, selem)
    # Step 6: Closure operation with a disk of radius 10.
    # This operation is to keep nodules attached to the lung wall.
    selem = disk(10)  # CHANGE BACK TO 10
    binary = binary_closing(binary, selem)
    # Step 7: Fill in the small holes inside the binary mask of lungs.
    edges = roberts(binary)
    binary = scipy.ndimage.binary_fill_holes(edges)
    # Step 8: Superimpose the binary mask on the input image.
    get_high_vals = binary == 0
    im[get_high_vals] = -2000
    return im, binary
コード例 #19
0
    def extract_lung_img_2D(self, im, plot=False):
        binary = im < -550
        cleared = segmentation.clear_border(binary)
        label_image = measure.label(cleared)
        areas = [r.area for r in measure.regionprops(label_image)]
        areas.sort()
        if len(areas) > 2:
            for region in measure.regionprops(label_image):
                if region.area < areas[-2]:
                    for coordinates in region.coords:
                        label_image[coordinates[0], coordinates[1]] = 0
        binary = label_image > 0

        selem = morphology.disk(2)
        binary = morphology.binary_erosion(binary, selem)

        selem = morphology.disk(10)
        binary = morphology.binary_closing(binary, selem)

        # #?
        # selem = morphology.disk(10)
        # binary = morphology.binary_dilation(binary, selem)

        edges = roberts(binary)
        binary = ndi.binary_fill_holes(edges)

        get_high_vals = binary == 0
        im[get_high_vals] = LUNG_MIN_BOUND
        return im
コード例 #20
0
def get_edges(image, thresshold=0.1):
    s = image.shape[0]
    image = np.reshape(image, (s, 28, 28))
    ret = np.zeros_like(image)
    for i in range(s):
        ret[i, :, :] = binarize(roberts(image[i, :, :]), thresshold)
    return np.reshape(ret, (s, 28 * 28))
コード例 #21
0
def segment_region_of_interest(image):
    """
    Looking into how to perform automated segmentation
    """
    binary = image < 604
    cleared = clear_border(binary)

    label_image = label(cleared)

    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                    label_image[coordinates[0], coordinates[1]] = 0

    binary = label_image > 0

    selem = disk(2)
    binary = binary_erosion(binary, selem)

    selem = disk(10)
    binary = binary_closing(binary, selem)

    edges = roberts(binary)
    binary = scipy.ndimage.binary_fill_holes(edges)

    get_high_vals = binary == 0
    image[get_high_vals] = 0

    return image
コード例 #22
0
def get_segmented_lungs(im):
    '''
    对输入的图像进行肺部区域分割,提取有效的肺部区域,用于模型训练
    :param 输入的图像
    :return: 返回分割结果
    '''

    binary = im < -400  # Step 1: 转换为二值化图像
    cleared = clear_border(binary)  # Step 2: 清除图像边界的小块区域
    label_image = label(cleared)  # Step 3: 分割图像

    areas = [r.area for r in regionprops(label_image)]  # Step 4: 保留2个最大的连通区域
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                    label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0

    selem = disk(2)  # Step 5: 图像腐蚀操作,将结节与血管剥离
    binary = binary_erosion(binary, selem)
    selem = disk(10)  # Step 6: 图像闭环操作,保留贴近肺壁的结节
    binary = binary_closing(binary, selem)
    edges = roberts(binary)  # Step 7: 进一步将肺区残余小孔区域填充
    binary = ndi.binary_fill_holes(edges)
    get_high_vals = binary == 0  # Step 8: 将二值化图像叠加到输入图像上
    im[get_high_vals] = -2000
    print('lung segmentation complete.')
    return im, binary
コード例 #23
0
ファイル: basical.py プロジェクト: AirChen/somesiteOpen
    def ski_filter(self):
        im = list(self.img.getdata())
        robert_edge = roberts(im)
        im = Image.fromarray(cm.gist_earth(robert_edge, bytes=True))
        self.img = Image.new("RGB", im.size, (255, 255, 255))

        return self
コード例 #24
0
def segmentation(file_name):
    data_x, data_y, data_z = get_data(file_name)
    shape_x = len(np.unique(data_x))
    shape_y = len(np.unique(data_y))
    X = data_x.reshape(shape_x, shape_y)
    Y = data_y.reshape(shape_x, shape_y)
    Z = data_z.reshape(shape_x, shape_y)

    markers = np.zeros_like(Z)
    markers[Z < 0.15] = 1
    markers[Z > 0.3] = 2
    elevation_map = roberts(Z)
    fig, (ax1, ax2) = plt.subplots(1,
                                   2,
                                   figsize=(6, 3),
                                   sharex=True,
                                   sharey=True)
    # ax.imshow(Z)
    # ax.imshow(elevation_map, cmap=plt.cm.jet, interpolation='nearest')
    segmentation = watershed(elevation_map, markers)
    ax2.imshow(segmentation, interpolation='nearest')
    # ax.axis('off')
    # ax.set_title('segmentation')
    segmentation = ndi.binary_fill_holes(segmentation - 1)
    labeled_coins, _ = ndi.label(segmentation)
    ax1.imshow(Z, cmap=plt.cm.gray, interpolation='nearest')
    ax1.contour(segmentation, [0.5], linewidths=1.2, colors='y')
    ax1.axis('off')
    ax1.set_adjustable('box-forced')

    plt.show()
コード例 #25
0
def get_segmented_lungs(im):
    # Convert into a binary image.
    binary = im < 604

    # Remove the blobs connected to the border of the image
    cleared = clear_border(binary)
    # Label the image
    label_image = label(cleared)
    # Keep the labels with 2 largest areas
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                    label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    # Closure operation with disk of radius 12
    selem = disk(2)
    binary = binary_erosion(binary, selem)

    selem = disk(10)
    binary = binary_closing(binary, selem)

    # Fill in the small holes inside the lungs
    edges = roberts(binary)
    binary = ndi.binary_fill_holes(edges)
    # Superimpose the mask on the input image
    get_high_vals = binary == 0
    im[get_high_vals] = 0

    return im
コード例 #26
0
def apply_pipeline(im, pipeline):
    for pip in pipeline:
        name = pip['name']
        pms = pip['params']
        if (name == 'gabor'):
            im = filters.gabor(im,
                               frequency=pms['frequency'],
                               theta=pms['theta'],
                               bandwidth=pms['bandwidth'],
                               mode=pms['mode'])
        elif (name == 'gaussian'):
            im = filters.gaussian(im,
                                  sigma=float(pms['sigma']),
                                  mode=pms['mode'])
        elif (name == 'median'):
            im = filters.median(im)
        elif (name == 'scharr'):
            im = filters.scharr(im)
        elif (name == 'roberts'):
            im = filters.roberts(im)
        # Morphology
        elif (name == 'closing'):
            im = morphology.closing(im)
        elif (name == 'dilation'):
            im = morphology.dilation(im)
        elif (name == 'erosion'):
            im = morphology.erosion(im)
        elif (name == 'opening'):
            im = morphology.opening(im)
        # Transforms
        elif (name == 'rgb2gray'):
            im = color.rgb2gray(im)
        else:
            print '$$$ Error: ' + name + ' not valid kernel.'
    return im
コード例 #27
0
ファイル: filter_spatial.py プロジェクト: yunjunz/PySAR
def filter(data,filtType,par):

    if   filtType == "sobel":       filt_data = sobel(data)
    elif filtType == "roberts":     filt_data = roberts(data)
    elif filtType == "canny":       filt_data = canny(data)
    elif filtType == "lowpass_avg":
        from scipy import ndimage
        p=int(par)
        kernel = np.ones((p,p),np.float32)/(p*p)
        filt_data = ndimage.convolve(data, kernel)
    elif filtType == "highpass_avg":
        from scipy import ndimage
        p=int(par)
        kernel = np.ones((p,p),np.float32)/(p*p)
        lp_data = ndimage.convolve(data, kernel)
        filt_data = data - lp_data
    elif filtType == "lowpass_gaussian":
        filt_data = gaussian(data, sigma=float(par))
    elif filtType == "highpass_gaussian":
        lp_data   = gaussian(data, sigma=float(par))
        filt_data = data - lp_data

    #elif filtType ==  "gradient":
       
    return filt_data
コード例 #28
0
ファイル: helpers.py プロジェクト: ericsolo/python
def get_segmented_lungs(im, plot=False):
    # Step 1: Convert into a binary image.
    binary = im < -400
    # Step 2: Remove the blobs connected to the border of the image.
    cleared = clear_border(binary)
    # Step 3: Label the image.
    label_image = label(cleared)
    # Step 4: Keep the labels with 2 largest areas.
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                       label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0
    # Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
    selem = disk(2)
    binary = binary_erosion(binary, selem)
    # Step 6: Closure operation with a disk of radius 10. This operation is    to keep nodules attached to the lung wall.
    selem = disk(10) # CHANGE BACK TO 10
    binary = binary_closing(binary, selem)
    # Step 7: Fill in the small holes inside the binary mask of lungs.
    edges = roberts(binary)
    binary = ndi.binary_fill_holes(edges)
    # Step 8: Superimpose the binary mask on the input image.
    get_high_vals = binary == 0
    im[get_high_vals] = -2000
    return im, binary
コード例 #29
0
def show_diff_edge_detectors(img):
    matplotlib.rcParams['font.size'] = 8
    edge_roberts = roberts(img)
    edge_sobel = sobel(img)
    edge_scharr = scharr(img)
    edge_prewitt = prewitt(img)
    canny = feature.canny(img, sigma=0.5)

    fig, axes = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True,
                             figsize=(10, 7))
    ax = axes.ravel()

    ax[0].imshow(img)
    ax[0].set_title('Input image')
    
    ax[1].imshow(edge_prewitt)
    ax[1].set_title('Prewitt Edge Detection')

    ax[2].imshow(edge_scharr)
    ax[2].set_title('Scharr Edge Detection')

    ax[3].imshow(edge_sobel)
    ax[3].set_title('Sobel Edge Detection')

    ax[4].imshow(edge_roberts)
    ax[4].set_title('Roberts Edge Detection')
    
    ax[5].imshow(canny)
    ax[5].set_title('Canny Edge Detection')

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

    plt.tight_layout()
    plt.show()
コード例 #30
0
def show_diff_cannies(img):
    matplotlib.rcParams['font.size'] = 8
    canny1 = feature.canny(img, sigma=0.01)
    canny2 = feature.canny(img, sigma=0.05)
    canny3 = feature.canny(img, sigma=0.1)
    canny4 = roberts(img)
    canny5 = sobel(img)

    fig, axes = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True,
                             figsize=(10, 7))
    ax = axes.ravel()

    ax[0].imshow(img)
    ax[0].set_title('Input image')
    ax[1].imshow(canny1)
    ax[2].imshow(canny2)
    ax[3].imshow(canny3)
    ax[4].imshow(canny4)
    ax[5].imshow(canny5)

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

    plt.tight_layout()
    plt.show()
コード例 #31
0
def get_segmented_lungs(im, plot=False, THRESHOLD=-320):

    binary = im < THRESHOLD

    cleared = clear_border(binary)

    label_image = measure.label(cleared)

    areas = [r.area for r in measure.regionprops(label_image)]
    areas.sort()
    #print areas
    if len(areas) > 2:
        for region in measure.regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                    label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0

    selem = morphology.disk(2)
    binary = morphology.binary_erosion(binary, selem)

    selem = morphology.disk(15)
    binary = morphology.binary_closing(binary, selem)

    edges = filters.roberts(binary)
    binary = binary_fill_holes(edges)

    get_high_vals = binary == 0
    im[get_high_vals] = 0

    return im
コード例 #32
0
def test():

    image = cv2.imread(path("../data/pikaqiu.jpg"), 0)
    edge_roberts = filters.roberts(image)
    edge_sobel = filters.sobel(image)
    implot(edge_sobel)
    implot(edge_roberts)
コード例 #33
0
ファイル: data_roifull1.py プロジェクト: skconsulting/ild
def get_segmented_lungs(im):

    binary = im < -320
    cleared = clear_border(binary) 
    cleared=morph(cleared,5)
    label_image = label(cleared)
  
    areas = [r.area for r in regionprops(label_image)]
    areas.sort()
    if len(areas) > 2:
        for region in regionprops(label_image):
            if region.area < areas[-2]:
                for coordinates in region.coords:
                       label_image[coordinates[0], coordinates[1]] = 0
    binary = label_image > 0  
    selem = disk(2)
    binary = binary_erosion(binary, selem)
 
    selem = disk(10)
    binary = binary_closing(binary, selem)
    edges = roberts(binary)
    binary = ndi.binary_fill_holes(edges)
 
    get_high_vals = binary == 0
    im[get_high_vals] = 0
  
    binary = morphology.dilation(binary,np.ones([5,5]))
    return binary
コード例 #34
0
    def colorVessels(self,binary_ves,color_depthMAT):
        ###########################################################################
        ## Colouring the vessels based on depth.
        ###########################################################################
        rows,cols = binary_ves.shape

        edge1 = roberts(binary_ves)
        edge2,edge3 = np.gradient(color_depthMAT)

        animateFlow.distance = ndimage.distance_transform_cdt(binary_ves , return_distances=True)
        animateFlow.distance=animateFlow.distance.transpose()

        animateFlow.width_ave=self.ave(animateFlow.distance)

        
        img = pygame.surfarray.make_surface(binary_ves).convert()
        for i in range(0,rows):
            for j in range(0,cols):
                if img.get_at((i,j))!=(0,0,0,255):
                    
                    if edge1[i][j]>0:
                        img.set_at((i,j),(120,120,120,180))
                    elif edge2[j][i] >= 1.2 * animateFlow.depth_range or edge3[j][i] >= 1.2 * animateFlow.depth_range:
                        img.set_at((i,j),(120,120,120,180))
                        
                    else:   
                        fill = 0
#      
                        i_c = -2
                        while i_c < 2 and fill == 0:
                            i_c += 1
                            j_c = -2
                            while j_c <2 and fill == 0:
                                j_c += 1
                                if 0 <= j+j_c < cols and 0 <= i+i_c < rows:
                                    if abs(color_depthMAT[j][i]-color_depthMAT[j+j_c][i+i_c]) < 1*animateFlow.depth_range and img.get_at((i,j))!=(0, 0, 85, 255):
                                        color = img.get_at((i,j))
                                        fill = 1
                                        break
                        if fill == 0:
                            if 0<color_depthMAT[j][i]<=40:
                                color = (255,0,0,180)
                            elif color_depthMAT[j][i]<=80:
                                color = (220,0,0,180)
                            elif color_depthMAT[j][i]<=120:
                                color = (200,0,0,180)
                            elif color_depthMAT[j][i]<=160:
                                color = (180,0,0,180)
                            elif color_depthMAT[j][i]<=200:
                                color = (150,0,0,180)
                            elif color_depthMAT[j][i]<=240:
                                color = (120,0,0,180)
                            else:
                                color = (100,0,0,180)
                            
         
                        img.set_at((i,j),color)
        
        return img
コード例 #35
0
ファイル: test_edges.py プロジェクト: lotteanna/scikit-image
def test_roberts_diagonal2():
    """Roberts' filter on a diagonal edge should be a diagonal line."""
    image = np.rot90(np.tri(10, 10, 0), 3)
    expected = ~np.rot90(np.tri(10, 10, -1).astype(bool) |
                         np.tri(10, 10, -2).astype(bool).transpose())
    expected = _mask_filter_result(expected, None)
    result = filters.roberts(image).astype(bool)
    assert_close(result, expected)
コード例 #36
0
ファイル: test_edges.py プロジェクト: Cadair/scikit-image
def test_roberts_diagonal1():
    """Roberts' filter on a diagonal edge should be a diagonal line."""
    image = np.tri(10, 10, 0)
    expected = ~(np.tri(10, 10, -1).astype(bool) |
                 np.tri(10, 10, -2).astype(bool).transpose())
    expected = _mask_filter_result(expected, None)
    result = filters.roberts(image).astype(bool)
    assert_array_almost_equal(result, expected)
コード例 #37
0
ファイル: test_edges.py プロジェクト: lizhuangliu/Pyto
def test_roberts_diagonal2():
    """Roberts' filter on a diagonal edge should be a diagonal line."""
    image = np.rot90(np.tri(10, 10, 0), 3)
    expected = ~np.rot90(np.tri(10, 10, -1).astype(bool) |
                         np.tri(10, 10, -2).astype(bool).transpose())
    expected = _mask_filter_result(expected, None)
    result = filters.roberts(image).astype(bool)
    assert_array_almost_equal(result, expected)
コード例 #38
0
ファイル: image_utils.py プロジェクト: tivervac/UGentProjects
def edge_detection(image):
    edge_roberts = roberts(image)
    fig, ax0 = plt.subplots()

    ax0.imshow(edge_roberts, cmap=plt.cm.gray)
    ax0.set_title('Roberts Edge Detection')
    ax0.axis('off')

    plt.tight_layout()
コード例 #39
0
ファイル: image_processing_lab.py プロジェクト: rostar/rostar
 def _get_edges(self):
     img_edg, mask = self.processed_image
     if self.edge_detection_method == 'canny':
         img_edg = canny(img_edg, sigma=self.canny_sigma,
                     low_threshold=self.canny_low,
                     high_threshold=self.canny_high)
     elif self.edge_detection_method == 'roberts':
         img_edg = roberts(img_edg)
     elif self.edge_detection_method == 'sobel':
         img_edg = sobel(img_edg)
     img_edg = img_edg > 0.0
     return img_edg
コード例 #40
0
def compareGreys(greyimage_before, greyimage_after, high_percentile=10, mid_percentile=20):

    assert greyimage_before.shape == greyimage_after.shape

    # get some edges
    edge_roberts_before = roberts(greyimage_before)
    edge_roberts_after = roberts(greyimage_after)

    # pca on the edge arrays
    delta = np.dstack([edge_roberts_after.ravel(), edge_roberts_before.ravel()])[0]
    pca = decomposition.PCA(n_components=2, whiten=False)
    pca.fit(delta)
    XY = pca.transform(delta)[:,1].reshape(greyimage_before.shape)

    # set areas below given percentile thresholds
    midperc = np.percentile(XY, mid_percentile)
    highperc = np.percentile(XY, high_percentile)

    out = np.zeros((XY.shape), dtype=np.uint8)

    out[np.where(XY <= midperc)] = 1
    out[np.where(XY <= highperc)] = 2

    return out
コード例 #41
0
ファイル: imgpro.py プロジェクト: eason001/imBot
def roberts_each(image):
    return filters.roberts(image)
コード例 #42
0
ファイル: imgpro.py プロジェクト: eason001/imBot
def roberts_hsv(image):
    return filters.roberts(image)
コード例 #43
0
ax2.imshow(edges1, cmap=plt.cm.gray)
ax2.axis('off')
ax2.set_title('Canny filter, $\sigma=1$', fontsize=20)

ax3.imshow(edges2, cmap=plt.cm.gray)
ax3.axis('off')
ax3.set_title('Canny filter, $\sigma=3$', fontsize=20)

fig.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9,
                    bottom=0.02, left=0.02, right=0.98)

plt.show()

# ROBERTS AND SOBEL EDGE DETECTION #############################################

edge_roberts = roberts(im)
edge_sobel = sobel(im)

fig, (ax0, ax1, ax2) = plt.subplots(ncols=3)

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

ax1.imshow(edge_roberts, cmap=plt.cm.gray)
ax1.set_title('Roberts Edge Detection')
ax1.axis('off')

ax2.imshow(edge_sobel, cmap=plt.cm.gray)
ax2.set_title('Sobel Edge Detection')
ax2.axis('off')
コード例 #44
0
from scipy import misc
from skimage import color
from skimage import measure
from skimage import io
from skimage.data import camera
from skimage.filters import roberts, sobel, scharr, prewitt

files = io.ImageCollection('../images/examples/pure/' + '*.JPG')
im = misc.imread(files.files[0])

# image_gray = color.rgb2gray(im)[0:100, 0:100]
image_gray = color.rgb2hsv(im)[:, :, 2][0:200, 0:200]

# image = camera()
edge_roberts = roberts(image_gray)
edge_sobel = sobel(image_gray)

fig, (ax0, ax1) = plt.subplots(ncols=2, sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})

ax0.imshow(edge_roberts, cmap=plt.cm.gray)
ax0.set_title('Roberts Edge Detection')
ax0.axis('off')

ax1.imshow(edge_sobel, cmap=plt.cm.gray)
ax1.set_title('Sobel Edge Detection')
ax1.axis('off')

plt.tight_layout()
plt.show()
コード例 #45
0
ファイル: initia_sailesh.py プロジェクト: sajal0jain/dsg
# display results
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8, 3),
                                    sharex=True, sharey=True)
ax1.imshow(img_name_gs, cmap=plt.cm.gray)
ax1.axis('off')
ax1.set_title('noisy image', fontsize=20)
ax2.imshow(edges1, cmap=plt.cm.gray)
ax2.axis('off')
ax2.set_title('Canny filter, $\sigma=1$', fontsize=20)
ax3.imshow(edges2, cmap=plt.cm.gray)
ax3.axis('off')
ax3.set_title('Canny filter, $\sigma=3$', fontsize=20)
fig.tight_layout()
plt.show()

edge_roberts = roberts(img_name_gs)
edge_sobel = sobel(img_name_gs)

fig, (ax0, ax1) = plt.subplots(ncols=2, sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})

ax0.imshow(edge_roberts, cmap=plt.cm.gray)
ax0.set_title('Roberts Edge Detection')
ax0.axis('off')

ax1.imshow(edge_sobel, cmap=plt.cm.gray)
ax1.set_title('Sobel Edge Detection')
ax1.axis('off')
plt.tight_layout()


edge_sobel = sobel(img_name_gs)
コード例 #46
0
ファイル: skimage_filters.py プロジェクト: kcavagnolo/ml_fun
plt.imshow(gauss)

gauss2=gaussian_filter(gray0, sigma=5, multichannel=True)
plt.imshow(gauss2)

lap=laplace(gray0,ksize=100)
plt.imshow(lap)

pre=prewitt(gray0, mask=None)
plt.imshow(pre)

pre_v=prewitt_v(gray0, mask=None)
plt.imshow(pre_v)

from skimage import filters
edges2 = filters.roberts(gray0)
plt.imshow(edges2)

plt.imshow(scharr(gray0))
plt.imshow(threshold_mean(gray0))
plt.imshow(wiener(gray0))

#######################################
plt.imshow(img)
plt.imshow(gray0)
plt.imshow(image)
### TREES
plt.imshow(segmentation)
### CONTOURS
plt.imshow(img_back, cmap = 'gray')
### STREET
コード例 #47
0
ファイル: grabseeds.py プロジェクト: tanghaibao/jcvi
def seeds(args):
    """
    %prog seeds [pngfile|jpgfile]

    Extract seed metrics from [pngfile|jpgfile]. Use --rows and --cols to crop image.
    """
    p = OptionParser(seeds.__doc__)
    p.set_outfile()
    opts, args, iopts = add_seeds_options(p, args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    pngfile, = args
    pf = opts.prefix or op.basename(pngfile).rsplit(".", 1)[0]
    sigma, kernel = opts.sigma, opts.kernel
    rows, cols = opts.rows, opts.cols
    labelrows, labelcols = opts.labelrows, opts.labelcols
    ff = opts.filter
    calib = opts.calibrate
    outdir = opts.outdir
    if outdir != '.':
        mkdir(outdir)
    if calib:
        calib = json.load(must_open(calib))
        pixel_cm_ratio, tr = calib["PixelCMratio"], calib["RGBtransform"]
        tr = np.array(tr)

    resizefile, mainfile, labelfile, exif = \
                      convert_image(pngfile, pf, outdir=outdir,
                                    rotate=opts.rotate,
                                    rows=rows, cols=cols,
                                    labelrows=labelrows, labelcols=labelcols)

    oimg = load_image(resizefile)
    img = load_image(mainfile)

    fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=4, nrows=1,
                                             figsize=(iopts.w, iopts.h))

    # Edge detection
    img_gray = rgb2gray(img)
    logging.debug("Running {0} edge detection ...".format(ff))
    if ff == "canny":
        edges = canny(img_gray, sigma=opts.sigma)
    elif ff == "roberts":
        edges = roberts(img_gray)
    elif ff == "sobel":
        edges = sobel(img_gray)
    edges = clear_border(edges, buffer_size=opts.border)
    selem = disk(kernel)
    closed = closing(edges, selem) if kernel else edges
    filled = binary_fill_holes(closed)

    # Watershed algorithm
    if opts.watershed:
        distance = distance_transform_edt(filled)
        local_maxi = peak_local_max(distance, threshold_rel=.05, indices=False)
        coordinates = peak_local_max(distance, threshold_rel=.05)
        markers, nmarkers = label(local_maxi, return_num=True)
        logging.debug("Identified {0} watershed markers".format(nmarkers))
        labels = watershed(closed, markers, mask=filled)
    else:
        labels = label(filled)

    # Object size filtering
    w, h = img_gray.shape
    canvas_size = w * h
    min_size = int(round(canvas_size * opts.minsize / 100))
    max_size = int(round(canvas_size * opts.maxsize / 100))
    logging.debug("Find objects with pixels between {0} ({1}%) and {2} ({3}%)"\
                    .format(min_size, opts.minsize, max_size, opts.maxsize))

    # Plotting
    ax1.set_title('Original picture')
    ax1.imshow(oimg)

    params = "{0}, $\sigma$={1}, $k$={2}".format(ff, sigma, kernel)
    if opts.watershed:
        params += ", watershed"
    ax2.set_title('Edge detection\n({0})'.format(params))
    closed = gray2rgb(closed)
    ax2_img = labels
    if opts.edges:
        ax2_img = closed
    elif opts.watershed:
        ax2.plot(coordinates[:, 1], coordinates[:, 0], 'g.')
    ax2.imshow(ax2_img, cmap=iopts.cmap)

    ax3.set_title('Object detection')
    ax3.imshow(img)

    filename = op.basename(pngfile)
    if labelfile:
        accession = extract_label(labelfile)
    else:
        accession = pf

    # Calculate region properties
    rp = regionprops(labels)
    rp = [x for x in rp if min_size <= x.area <= max_size]
    nb_labels = len(rp)
    logging.debug("A total of {0} objects identified.".format(nb_labels))
    objects = []
    for i, props in enumerate(rp):
        i += 1
        if i > opts.count:
            break

        y0, x0 = props.centroid
        orientation = props.orientation
        major, minor = props.major_axis_length, props.minor_axis_length
        major_dx = cos(orientation) * major / 2
        major_dy = sin(orientation) * major / 2
        minor_dx = sin(orientation) * minor / 2
        minor_dy = cos(orientation) * minor / 2
        ax2.plot((x0 - major_dx, x0 + major_dx),
                 (y0 + major_dy, y0 - major_dy), 'r-')
        ax2.plot((x0 - minor_dx, x0 + minor_dx),
                 (y0 - minor_dy, y0 + minor_dy), 'r-')

        npixels = int(props.area)
        # Sample the center of the blob for color
        d = min(int(round(minor / 2 * .35)) + 1, 50)
        x0d, y0d = int(round(x0)), int(round(y0))
        square = img[(y0d - d):(y0d + d), (x0d - d):(x0d + d)]
        pixels = []
        for row in square:
            pixels.extend(row)
        logging.debug("Seed #{0}: {1} pixels ({2} sampled) - {3:.2f}%".\
                        format(i, npixels, len(pixels), 100. * npixels / canvas_size))

        rgb = pixel_stats(pixels)
        objects.append(Seed(filename, accession, i, rgb, props, exif))
        minr, minc, maxr, maxc = props.bbox
        rect = Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, ec='w', lw=1)
        ax3.add_patch(rect)
        mc, mr = (minc + maxc) / 2, (minr + maxr) / 2
        ax3.text(mc, mr, "{0}".format(i), color='w',
                    ha="center", va="center", size=6)

    for ax in (ax2, ax3):
        ax.set_xlim(0, h)
        ax.set_ylim(w, 0)

    # Output identified seed stats
    ax4.text(.1, .92, "File: {0}".format(latex(filename)), color='g')
    ax4.text(.1, .86, "Label: {0}".format(latex(accession)), color='m')
    yy = .8
    fw = must_open(opts.outfile, "w")
    if not opts.noheader:
        print(Seed.header(calibrate=calib), file=fw)
    for o in objects:
        if calib:
            o.calibrate(pixel_cm_ratio, tr)
        print(o, file=fw)
        i = o.seedno
        if i > 7:
            continue
        ax4.text(.01, yy, str(i), va="center", bbox=dict(fc='none', ec='k'))
        ax4.text(.1, yy, o.pixeltag, va="center")
        yy -= .04
        ax4.add_patch(Rectangle((.1, yy - .025), .12, .05, lw=0,
                      fc=rgb_to_hex(o.rgb)))
        ax4.text(.27, yy, o.hashtag, va="center")
        yy -= .06
    ax4.text(.1 , yy, "(A total of {0} objects displayed)".format(nb_labels),
             color="darkslategrey")
    normalize_axes(ax4)

    for ax in (ax1, ax2, ax3):
        xticklabels = [int(x) for x in ax.get_xticks()]
        yticklabels = [int(x) for x in ax.get_yticks()]
        ax.set_xticklabels(xticklabels, family='Helvetica', size=8)
        ax.set_yticklabels(yticklabels, family='Helvetica', size=8)

    image_name = op.join(outdir, pf + "." + iopts.format)
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
    return objects
コード例 #48
0
ファイル: Inverse_Filtering.py プロジェクト: Yue93/PID
def getEdge(img,mode=0):
    return {0: sobel(img),
        1:scharr(img),
        2:prewitt(img),
        3:roberts(img)}.get(mode, sobel(img))
コード例 #49
0
def edgedetection(image=None):
    """

    http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.canny
    http://stackoverflow.com/questions/29434533/edge-detection-for-image-stored-in-matrix

    """

    import numpy as np
    from matplotlib import pyplot as plt
    from scipy import ndimage

    from skimage import feature
    from skimage.filters import roberts, sobel, scharr, prewitt

    image_save = image

    # for convenience
    im = image


    # Compute the Canny filter for two values of sigma
    # http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.cannya

    print('Image pixel value range:', np.min(im), np.max(im))
    edges1 = feature.canny(im, sigma=0.0,
                           low_threshold=0.0, high_threshold=5.0)

    # display results
    fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(16, 6),
                                        sharex=True, sharey=True)

    ax1.imshow(im, cmap=plt.cm.gray)
    ax1.axis('off')
    ax1.set_title('noisy image', fontsize=20)

    ax2.imshow(edges1, cmap=plt.cm.gray)
    ax2.axis('off')
    ax2.set_title('Canny filter \n $\sigma=0.0$', fontsize=20)

    fig.tight_layout()

    plt.show()

    # could try sobel filter
    # http://scikit-image.org/docs/dev/auto_examples/plot_edge_filter.html

    image = im
    edge_roberts = roberts(image)
    edge_sobel = sobel(image)

    fig, (ax0, ax1) = plt.subplots(ncols=2,
                                   sharex=True, sharey=True,
                                   subplot_kw={'adjustable':'box-forced'})

    ax0.imshow(edge_roberts, cmap=plt.cm.gray)
    ax0.set_title('Roberts Edge Detection')
    ax0.axis('off')

    ax1.imshow(edge_sobel, cmap=plt.cm.gray)
    ax1.set_title('Sobel Edge Detection')
    ax1.axis('off')

    plt.tight_layout()

    plt.show()


    # http://www.scipy-lectures.org/advanced/image_processing/auto_examples/plot_find_edges.html
    """
    Finding edges with Sobel filters
    ==================================

    The Sobel filter is one of the simplest way of finding edges.
    """

    import numpy as np
    from scipy import ndimage
    import matplotlib.pyplot as plt

    im = np.zeros((256, 256))
    im[64:-64, 64:-64] = 1

    im = ndimage.rotate(im, 15, mode='constant')
    im = ndimage.gaussian_filter(im, 8)

    sx = ndimage.sobel(im, axis=0, mode='constant')
    sy = ndimage.sobel(im, axis=1, mode='constant')
    sob = np.hypot(sx, sy)

    plt.figure(figsize=(16, 6))
    plt.subplot(141)
    plt.imshow(im, cmap=plt.cm.gray)
    plt.axis('off')
    plt.title('square', fontsize=20)
    plt.subplot(142)
    plt.imshow(sx)
    plt.axis('off')
    plt.title('Sobel (x direction)', fontsize=20)
    plt.subplot(143)
    plt.imshow(sob)
    plt.axis('off')
    plt.title('Sobel filter', fontsize=20)

    im += 0.07*np.random.random(im.shape)

    sx = ndimage.sobel(im, axis=0, mode='constant')
    sy = ndimage.sobel(im, axis=1, mode='constant')
    sob = np.hypot(sx, sy)

    plt.subplot(144)
    plt.imshow(sob)
    plt.axis('off')
    plt.title('Sobel for noisy image', fontsize=20)

    plt.subplots_adjust(wspace=0.02, hspace=0.02,
                        top=1, bottom=0, left=0, right=0.9)

    plt.show()


    # now apply to our image
    im = image_save

    sx = ndimage.sobel(im, axis=0, mode='constant')
    sy = ndimage.sobel(im, axis=1, mode='constant')
    sob = np.hypot(sx, sy)

    plt.figure(figsize=(16, 6))
    plt.subplot(141)
    plt.imshow(im, cmap=plt.cm.gray)
    plt.axis('off')
    plt.title('square', fontsize=20)
    plt.subplot(142)
    plt.imshow(sx)
    plt.axis('off')
    plt.title('Sobel (x direction)', fontsize=20)
    plt.subplot(143)
    plt.imshow(sob)
    plt.axis('off')
    plt.title('Sobel filter', fontsize=20)

    sx = ndimage.sobel(im, axis=0, mode='constant')
    sy = ndimage.sobel(im, axis=1, mode='constant')
    sob = np.hypot(sx, sy)

    plt.subplot(144)
    plt.imshow(sob)
    plt.axis('off')
    plt.title('Sobel for noisy image', fontsize=20)

    plt.subplots_adjust(wspace=0.02, hspace=0.02,
                        top=1, bottom=0, left=0, right=0.9)

    plt.show()



    # http://www.scipy-lectures.org/advanced/image_processing/auto_examples/plot_clean_morpho.html
    # plot_clean_morpho.py


    # def make_image():
    # """
    #
    # """

    np.random.seed(1)
    n = 10
    l = 256
    im = np.zeros((l, l))
    points = l*np.random.random((2, n**2))
    im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
    im = ndimage.gaussian_filter(im, sigma=l/(4.*n))

    mask = (im > im.mean()).astype(np.float)


    img = mask + 0.3*np.random.randn(*mask.shape)

    binary_img = img > 0.5

    # Remove small white regions
    open_img = ndimage.binary_opening(binary_img)
    # Remove small black hole
    close_img = ndimage.binary_closing(open_img)

    plt.figure(figsize=(16, 4))

    l = 128

    plt.subplot(141)
    plt.imshow(binary_img[:l, :l], cmap=plt.cm.gray)
    plt.axis('off')
    plt.subplot(142)
    plt.imshow(open_img[:l, :l], cmap=plt.cm.gray)
    plt.axis('off')
    plt.subplot(143)
    plt.imshow(close_img[:l, :l], cmap=plt.cm.gray)
    plt.axis('off')
    plt.subplot(144)
    plt.imshow(mask[:l, :l], cmap=plt.cm.gray)

    plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors='r')

    plt.axis('off')

    plt.subplots_adjust(wspace=0.02, hspace=0.3,
                        top=1, bottom=0.1, left=0, right=1)

    plt.show()

    # http://stackoverflow.com/questions/1560424/how-can-i-get-the-x-y-values-of-the-line-that-is-ploted-by-a-contour-plot-mat
    # http://stackoverflow.com/questions/5666056/matplotlib-extracting-data-from-contour-lines


     # from http://stackoverflow.com/questions/29434533/edge-detection-for-image-stored-in-matrix
    thresh1 = 1
    thresh2 = 2

    #Load image
    # im = sp.misc.imread('jBD9j.png')

    im = image_save
    #Get threashold mask for different regions
    gryim = np.mean(im[:,:,0:2],2)
    region1 =  (thresh1 < gryim)
    region2 =  (thresh2 < gryim)
    nregion1 = ~ region1
    nregion2 = ~ region2

    #Plot figure and two regions
    fig, axs = plt.subplots(2,2)
    axs[0,0].imshow(im)
    axs[0,1].imshow(region1)
    axs[1,0].imshow(region2)

    #Clean up any holes, etc (not needed for simple figures here)
    #region1 = sp.ndimage.morphology.binary_closing(region1)
    #region1 = sp.ndimage.morphology.binary_fill_holes(region1)
    #region1.astype('bool')
    #region2 = sp.ndimage.morphology.binary_closing(region2)
    #region2 = sp.ndimage.morphology.binary_fill_holes(region2)
    #region2.astype('bool')

    #Get location of edge by comparing array to it's
    #inverse shifted by a few pixels
    shift = -2
    edgex1 = (region1 ^ np.roll(nregion1,shift=shift,axis=0))
    edgey1 = (region1 ^ np.roll(nregion1,shift=shift,axis=1))
    edgex2 = (region2 ^ np.roll(nregion2,shift=shift,axis=0))
    edgey2 = (region2 ^ np.roll(nregion2,shift=shift,axis=1))

    #Plot location of edge over image
    axs[1,1].imshow(im)
    axs[1,1].contour(edgex1,2,colors='r',lw=2.)
    axs[1,1].contour(edgey1,2,colors='r',lw=2.)
    axs[1,1].contour(edgex2,2,colors='g',lw=2.)
    axs[1,1].contour(edgey2,2,colors='g',lw=2.)
コード例 #50
0
ファイル: test_edges.py プロジェクト: lotteanna/scikit-image
def test_roberts_zeros():
    """Roberts' filter on an array of all zeros."""
    result = filters.roberts(np.zeros((10, 10)), np.ones((10, 10), bool))
    assert (np.all(result == 0))
コード例 #51
0
ファイル: imgpro.py プロジェクト: eason001/imBot
def roberts_gray(image):
    return filters.roberts(image)
コード例 #52
0
==============

Edge operators are used in image processing within edge detection algorithms.
They are discrete differentiation operators, computing an approximation of the
gradient of the image intensity function.

"""
import numpy as np
import matplotlib.pyplot as plt

from skimage.data import camera
from skimage.filters import roberts, sobel, scharr, prewitt


image = camera()
edge_roberts = roberts(image)
edge_sobel = sobel(image)

fig, (ax0, ax1) = plt.subplots(ncols=2, sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})

ax0.imshow(edge_roberts, cmap=plt.cm.gray)
ax0.set_title('Roberts Edge Detection')
ax0.axis('off')

ax1.imshow(edge_sobel, cmap=plt.cm.gray)
ax1.set_title('Sobel Edge Detection')
ax1.axis('off')

plt.tight_layout()

"""
コード例 #53
0
ファイル: image.py プロジェクト: JorgeDeLosSantos/NanchiPlot
def roberts(X):
    rb = filters.roberts(X)
    return rb
コード例 #54
0
def RobersMetric(self, field, unused_opts):
  return filters.roberts(numpy.abs(field))
コード例 #55
-1
def detect_edges(imagename, algorithm):
    '''
    Does edge detection by the choosen algorithm.

    :param imagename: image name
    :param algorithm: has to be "roberts", "scharr", "prewitt", "canny-1", "canny-2" or "canny3"
    :returns: image
    '''

    im = color.rgb2gray(imagename)  # image is colored, lets make it gray scale
    logging.info(algorithm + ' was choosen as edge detection algorithm.')
    if algorithm == "roberts":
        edges = filters.roberts(im)
    elif algorithm == "scharr":
        edges = filters.scharr(im)
    elif algorithm == "sobel":
        edges = filters.sobel(im)
    elif algorithm == "prewitt":
        edges = filters.prewitt(im)
    elif algorithm == "canny-1":
        edges = feature.canny(im, sigma=1)
    elif algorithm == "canny-2":
        edges = feature.canny(im, sigma=2)
    elif algorithm == "canny-3":
        edges = feature.canny(im, sigma=3)
    return edges