コード例 #1
1
def main():
    """Load image, apply filter, plot."""
    img = data.camera()

    # just like sobel, but no -2/+2 in the middle
    prewitt_y = np.array([
        [-1, -1, -1],
        [0, 0, 0],
        [1, 1, 1]
    ])
    prewitt_x = np.rot90(prewitt_y) # rotates counter-clockwise

    img_sx = signal.correlate(img, prewitt_x, mode="same")
    img_sy = signal.correlate(img, prewitt_y, mode="same")
    g_magnitude = np.sqrt(img_sx**2 + img_sy**2)

    ground_truth = skifilters.prewitt(data.camera())

    util.plot_images_grayscale(
        [img, img_sx, img_sy, g_magnitude, ground_truth],
        ["Image", "Prewitt (x)", "Prewitt (y)", "Prewitt (both/magnitude)",
         "Prewitt (Ground Truth)"]
    )
コード例 #2
0
def process_frame(frame, ref, wettedArea, theta, threshold1, threshold2):
    """    
    Compare the frame of interest to a reference frame and already known 
    wetted area and determine what additional areas have becomed wetted using
    the absolute difference and the difference in edge detection.
    """
    # For testing and optimizing, use these flags to turn off either step
    simpleSubtraction = True
    edgeSubtraction = True
    cutoff = 254

    # Initialize storage variables
    image1 = np.zeros_like(frame)
    image2 = np.zeros_like(frame)
    tempRef = np.zeros_like(frame)
    comp1 = np.zeros_like(ref)
    comp2 = np.zeros_like(ref)

    # Generate comparison data between reference and image
    if simpleSubtraction:
        image1 = subtract_images(frame, ref)
    if edgeSubtraction:
        tempFrame = np.uint8(filters.prewitt(frame) * 255)
        tempRef = np.uint8(filters.prewitt(ref) * 255)
        image2 = subtract_images(tempFrame, tempRef)

    # Prepare matrices for thresholding the results
    # Apply different thresholds at different intensities
    comp1[:] = threshold1
    comp2[:] = threshold2
    #    comp1[ref>=30] = threshold1
    #    comp1[ref<30] = 2*threshold1
    #    comp2[tempRef<=128] = threshold2
    #    comp2[tempRef>128] = 2*threshold2
    #    comp2[tempRef<30] = threshold2*.75

    # Convert the results to 8 bit images for combining
    image1 = np.uint8((image1 > comp1) * 255)
    image2 = np.uint8((image2 > threshold2) * 255)
    #    wettedArea = np.uint8(wettedArea*255)

    # Depending on whether or not the disk is rotating, apply thresholding
    if theta != 0:
        image1 = rotate_image(image1, theta, size=image1.shape)
        image2 = rotate_image(image2, theta, size=image2.shape)

    wettedArea = wettedArea + (image1 > cutoff) + (image2 > cutoff)

    # Fill holes in the wetted area
    #    wettedArea = ndimage.morphology.binary_fill_holes(wettedArea)

    return wettedArea
コード例 #3
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)
コード例 #4
0
ファイル: metrics.py プロジェクト: connectsoumya/SRNRAR
def _gms(x_pred, x_real, c):
    """

    :rtype: np.ndarray
    """
    def rgb2gray(rgb):
        r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
        gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
        return gray

    grad_pred = np.zeros(shape=x_pred.shape[:3])
    grad_real = np.zeros(shape=x_real.shape[:3])
    if len(x_pred.shape) == 4 and x_pred.shape[-1] == 3:
        for i in range(x_pred.shape[0]):
            grad_pred[i, :, :] = prewitt(rgb2gray(x_pred[i, :, :, :]))
            grad_real[i, :, :] = prewitt(rgb2gray(x_real[i, :, :, :]))
    elif len(x_pred.shape) == 3 and x_pred.shape[-1] == 3:
        grad_pred = prewitt(rgb2gray(x_pred))
        grad_real = prewitt(rgb2gray(x_real))
    elif len(x_pred.shape) == 4 and x_pred.shape[-1] == 1:
        for i in range(x_pred.shape[0]):
            grad_pred[i, :, :] = prewitt(x_pred[i, :, :, 0])
            grad_real[i, :, :] = prewitt(x_real[i, :, :, 0])
    elif len(x_pred.shape) == 3 and x_pred.shape[-1] == 1:
        grad_pred = prewitt(x_pred)
        grad_real = prewitt(x_real)
    else:
        raise ValueError(
            'Check the function in the source code. You might need to develop this condition.'
        )

    gms = (2 * grad_real * grad_pred + c) / (grad_real**2 + grad_pred**2 + c)
    return gms
コード例 #5
0
def getEdge(img, mode=0):
    return {
        0: sobel(img),
        1: scharr(img),
        2: prewitt(img),
        3: roberts(img)
    }.get(mode, sobel(img))
コード例 #6
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()
コード例 #7
0
    def search_satellite(self, point, polygon):
        polygon_path = Path(polygon, closed=True)  # ?
        image = self.utils.center_image("satellite", point,
                                        self.zoom)  # /samples/staticmap2
        masked_image = self.utils.mask_image(image, polygon)  # masked image
        grayscale_image = self.utils.grayscale(
            masked_image)  # grayscaled masked image
        lot_paths = []

        edge_image = filters.prewitt(
            grayscale_image)  # image with prewitt operator applied
        edge_regions = self.regions.search(edge_image)  # 4 region boxes

        for region in edge_regions:
            region_image = masked_image[region[0][0]:region[1][0],
                                        region[0][1]:region[1]
                                        [1], :]  # splice image into regions
            profile = self.profiler.profile(region_image)  # ???

            if profile == PolygonProfile.LOT:
                bbox = self.utils.region_to_bbox(region)
                lot_paths.append(polygon_path.clip_to_bbox(bbox, inside=True))

        if self.debug and len(lot_paths) > 0:
            self.utils.draw_path_on_image(image, lot_paths)

        return lot_paths
コード例 #8
0
def filter():
    phasenames = ['train', 'val']
    tr = 0
    idx = 0
    cnttxt = 0
    cntnon = 0
    for phase in [0, 1]:
        f = open('%s_unbalance.txt' % (phasenames[phase]), 'r')
        f2 = open('%s.txt' % (phasenames[phase]), 'w')
        for s in f:
            if s.split(' ')[1][0] == '0':
                imgname = '%s%s' % (base, s.split(' ')[0])
                print(imgname)
                im = io.imread(imgname, as_grey=True)
                e = prewitt(im)
                emax = np.amax(e) / 2
                et = np.reshape(
                    np.array([0 if e1 < emax else 1 for e1 in e.flatten()]),
                    (32, 32))
                ecnt = np.sum(et)
                if ecnt > thresh:
                    f2.write(s)
                    tr = tr + (1 if (phase == 0) else 0)
                    idx = idx + 1
                    cntnon = cntnon + 1
            else:
                f2.write(s)
                tr = tr + (1 if (phase == 0) else 0)
                idx = idx + 1
                cnttxt = cnttxt + 1
        f.close()
        f2.close()
    print('total=', idx, ' training=', tr, ' Val=', idx - tr)
    print('Text=', cnttxt, ' non-Text=', cntnon)
コード例 #9
0
ファイル: test_edges.py プロジェクト: rfezzani/scikit-image
def test_prewitt_vertical():
    """Prewitt on a vertical edge should be a vertical line."""
    i, j = np.mgrid[-5:6, -5:6]
    image = (j >= 0).astype(float)
    result = filters.prewitt(image) * np.sqrt(2)
    assert_allclose(result[j == 0], 1)
    assert_allclose(result[np.abs(j) > 1], 0, atol=1e-10)
コード例 #10
0
ファイル: test_edges.py プロジェクト: rfezzani/scikit-image
def test_prewitt_mask(dtype):
    """Prewitt on a masked array should be zero."""
    result = filters.prewitt(
        np.random.uniform(size=(10, 10)).astype(dtype),
        np.zeros((10, 10), dtype=bool))
    assert result.dtype == _supported_float_type(dtype)
    assert_allclose(np.abs(result), 0)
コード例 #11
0
def preprocess_and_extract_features(data):
    '''Preprocess data and extract features

    Preprocess: normalize, scale, repair
    Extract features: transformations and dimensionality reduction
    '''
    # Here, we do something trivially simple: we take the average of the RGB
    # values to produce a grey image, transform that into a vector, then
    # extract the mean and standard deviation as features.

    # Make the image grayscale
    #data = np.mean(data, axis=3)
    data1 = []
    for row in range(data.shape[0]):
        data_4loop = prewitt(data[row])
        data1.append(data_4loop)
    data = np.array(data1)
    data[data > 140] = 255
    #np.clip(data, 0, 170, out=data)
    # Vectorize the grayscale matrices
    vectorized_data = data.reshape(data.shape[0], -1)

    # extract the mean and standard deviation of each sample as features
    feature_mean = np.mean(vectorized_data, axis=1)
    feature_std = np.std(vectorized_data, axis=1)
    feature_variance = np.var(vectorized_data, axis=1)

    # RED Combine the extracted features into a single feature vector
    features = np.stack((feature_mean, feature_std), axis=-1)

    return features
コード例 #12
0
def border_thing(Array, n):
    # Array ya está recortado
    res = []
    for joder in range(n):
        img = Array[joder]
        img_g = rgb2gray(img)

        # aplicación de filtros
        for k in range(0, 10):
            img_g = gaussian(img_g, 3)

        img_prw = prewitt(img_g, mask=None)
        #figure();
        #imshow(img_prw, cmap = "gray");
        #title("prewitt");
        #figure();
        #hist(img_prw.ravel(), 256, [0,256]);

        us_img = (255 * img_prw < 0.67).astype("uint8")
        #figure();
        #imshow(us_img, cmap = "gray");
        #title("umbralización");

        # conteo
        count = 0
        fil, col, can = img.shape
        for c in range(0, fil):
            for j in range(0, col):
                if (us_img[c][j] == 0):
                    count += 1

        res.append(count)

    return res
コード例 #13
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()
コード例 #14
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
コード例 #15
0
def edges(im):
    original = skimage.io.imread(im)
    grayscale = rgb2gray(original)
    edge_sobel = filters.sobel(grayscale)
    edge_scharr = filters.scharr(grayscale)
    edge_prewitt = filters.prewitt(grayscale)

    diff_scharr_prewitt = compare_images(edge_scharr, edge_prewitt)
    diff_scharr_sobel = compare_images(edge_scharr, edge_sobel)
    max_diff = np.max(np.maximum(diff_scharr_prewitt, diff_scharr_sobel))

    fig, axes = plt.subplots(nrows=2,
                             ncols=2,
                             sharex=True,
                             sharey=True,
                             figsize=(8, 8))
    axes = axes.ravel()

    # axes[0].imshow(im, cmap=plt.cm.gray)
    # axes[0].set_title('Original image')

    axes[1].imshow(edge_scharr, cmap=plt.cm.gray)
    axes[1].set_title('Scharr Edge Detection')

    axes[2].imshow(diff_scharr_prewitt, cmap=plt.cm.gray, vmax=max_diff)
    axes[2].set_title('Scharr - Prewitt')

    axes[3].imshow(diff_scharr_sobel, cmap=plt.cm.gray, vmax=max_diff)
    axes[3].set_title('Scharr - Sobel')

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

    plt.tight_layout()
    plt.show()
コード例 #16
0
ファイル: test_edges.py プロジェクト: rfezzani/scikit-image
def test_prewitt_horizontal():
    """Prewitt on an edge should be a horizontal line."""
    i, j = np.mgrid[-5:6, -5:6]
    image = (i >= 0).astype(float)
    result = filters.prewitt(image) * np.sqrt(2)
    # Check if result match transform direction
    assert (np.all(result[i == 0] == 1))
    assert_allclose(result[np.abs(i) > 1], 0, atol=1e-10)
コード例 #17
0
ファイル: test_edges.py プロジェクト: lotteanna/scikit-image
def test_prewitt_vertical():
    """Prewitt on a vertical edge should be a vertical line."""
    i, j = np.mgrid[-5:6, -5:6]
    image = (j >= 0).astype(float)
    result = filters.prewitt(image) * np.sqrt(2)
    j[np.abs(i) == 5] = 10000
    assert_allclose(result[j == 0], 1)
    assert_allclose(result[np.abs(j) > 1], 0, atol=1e-10)
コード例 #18
0
def sharp1(img, enhance, x):
    y = x.get()

    if (y == 1):
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        lap = cv2.Laplacian(img, cv2.CV_64F, ksize=5)
        im = Image.fromarray(lap)
        imgtk = ImageTk.PhotoImage(image=im, master=enhance)
        imglabel = tk.Label(enhance, image=imgtk)
        imglabel.image = imgtk
        imglabel.place(x=100, y=150)
    elif (y == 2):
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        n = img_as_float(img)
        robert = roberts(n)
        noise = img_as_ubyte(robert)
        im = Image.fromarray(noise)
        imgtk = ImageTk.PhotoImage(image=im, master=enhance)
        imglabel = tk.Label(enhance, image=imgtk)
        imglabel.image = imgtk
        imglabel.place(x=100, y=150)
    elif (y == 3):
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        n = img_as_float(img)
        sobe = sobel(n)
        noise = img_as_ubyte(sobe)
        im = Image.fromarray(noise)
        imgtk = ImageTk.PhotoImage(image=im, master=enhance)
        imglabel = tk.Label(enhance, image=imgtk)
        imglabel.image = imgtk
        imglabel.place(x=100, y=150)
    elif (y == 4):
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        edges = cv2.Canny(img, 100, 200)
        im = Image.fromarray(edges)
        imgtk = ImageTk.PhotoImage(image=im, master=enhance)
        imglabel = tk.Label(enhance, image=imgtk)
        imglabel.image = imgtk
        imglabel.place(x=100, y=150)
    elif (y == 5):
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        n = img_as_float(img)
        pre = prewitt(n)
        noise = img_as_ubyte(pre)
        im = Image.fromarray(noise)
        imgtk = ImageTk.PhotoImage(image=im, master=enhance)
        imglabel = tk.Label(enhance, image=imgtk)
        imglabel.image = imgtk
        imglabel.place(x=100, y=150)
    elif (y == 6):
        n = img_as_float(img)
        ma = unsharp_mask(n, radius=2, amount=2)
        noise = img_as_ubyte(ma)
        im = Image.fromarray(noise)
        imgtk = ImageTk.PhotoImage(image=im, master=enhance)
        imglabel = tk.Label(enhance, image=imgtk)
        imglabel.image = imgtk
        imglabel.place(x=100, y=150)
コード例 #19
0
def sys_prewitt(img):
    '''
    prewitt系统自带
    :param img: 原始图像
    :return: 返回边缘图像
    '''
    img = cv2.imread(img, 0)
    edge_img = filters.prewitt(img)
    return edge_img
コード例 #20
0
ファイル: test_edges.py プロジェクト: zlazri/scikit-image
def test_prewitt_horizontal():
    """Prewitt on an edge should be a horizontal line."""
    i, j = np.mgrid[-5:6, -5:6]
    image = (i >= 0).astype(float)
    result = filters.prewitt(image) * np.sqrt(2)
    # Fudge the eroded points
    i[np.abs(j) == 5] = 10000
    assert (np.all(result[i == 0] == 1))
    assert_allclose(result[np.abs(i) > 1], 0, atol=1e-10)
コード例 #21
0
ファイル: test_edges.py プロジェクト: lotteanna/scikit-image
def test_prewitt_horizontal():
    """Prewitt on an edge should be a horizontal line."""
    i, j = np.mgrid[-5:6, -5:6]
    image = (i >= 0).astype(float)
    result = filters.prewitt(image) * np.sqrt(2)
    # Fudge the eroded points
    i[np.abs(j) == 5] = 10000
    assert (np.all(result[i == 0] == 1))
    assert_allclose(result[np.abs(i) > 1], 0, atol=1e-10)
コード例 #22
0
ファイル: sk_image.py プロジェクト: JosiahMg/DailyExp
def show_img_edge():
    img = data.camera()
    edge_prewitt = prewitt(img)
    edge_sobel = sobel(img)
    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))

    # Prewitt 边缘检测
    ax1.imshow(edge_prewitt, cmap=plt.cm.gray)
    ax2.imshow(edge_sobel, cmap=plt.cm.gray)
    plt.show()
コード例 #23
0
 def edge_method(method_num, im, sigma=2):
     print("reached")
     return {
         1:feature.canny(im),
         2:feature.canny(im, sigma=2),
         3:roberts(im),
         4:sobel(im),
         5:scharr(im),
         6:prewitt(im)
     }[method_num]
コード例 #24
0
 def calculate_prewitt(self, X):
     trans = []
     for n in X:
         p = []
         for i in range(0, 50, 3):
             layer = n[:, :, i]
             p.append(prewitt(layer))
         trans.append(np.asarray(p))
     self.transformed = np.asarray(trans)
     return self
コード例 #25
0
ファイル: high_pass.py プロジェクト: GeovaneF55/pse-pid
def prewitt_rgb(image):
    """ Aplica o filtro Prewitt, utilizando o decorador
    @adapt_rgb para que o filtro seja aplicado em todos
    os canais RGB da imagem.

    @param image numpy.ndarray.

    @return result numpy.ndarray.
    """

    return filters.prewitt(image)
コード例 #26
0
ファイル: scoring.py プロジェクト: Hugggsy/LigneHT
def computeModels(img):
    '''Calcule les resultats des differentes methodes de detection d'objets'''
    #results = {'Image original': ing}
    results = {}
    results['Canny'] = feature.canny(img, sigma=1)
    results['Roberts'] = roberts(img)
    results['Sobel'] = sobel(img)
    results['Scharr'] = scharr(img)
    results['Prewitt'] = prewitt(img)
    results['Laplace'] = laplace(img)
    return results
コード例 #27
0
def Filtro4(matrix_imagem):
    #prewit
    #matrix_imagem=Filtro11(matrix_imagem)
    mask = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])

    mat_empty = np.zeros_like(matrix_imagem - matrix_imagem.min(),
                              dtype="uint16")
    for i in xrange(matrix_imagem.shape[0]):
        mat_empty[i] = filters.prewitt(matrix_imagem[i].astype("uint16") -
                                       matrix_imagem.min())
    return mat_empty.astype('int16') + matrix_imagem.min()
コード例 #28
0
    def get_result(self):
        '''
        The resulting image for each project (Picture 4 on the page). 
        '''
        arr = np.array(self.grayscale_pil)
        if self.pid == 1:
            if self.choice == 'ostu':
                self.option_value = threshold_otsu(arr)
            elif self.choice == 'entropy':
                self.option_value = threshold_li(arr)
            else:
                pass
            result_arr = (arr > self.option_value) * 255
        elif self.pid == 2:
            if self.choice == 'ED:Rob':
                result_arr = (1 - roberts(arr)) * 255.
            elif self.choice == 'ED:Prew':
                result_arr = (1 - prewitt(arr)) * 255.
            elif self.choice == 'ED:Sob':
                result_arr = (1 - sobel(arr)) * 255.
            elif self.choice == 'NR:gaus':
                result_arr = gaussian(arr, sigma=self.option_value) * 255.
            elif self.choice == 'NR:med':
                result_arr = median(arr, disk(self.option_value))
            else:
                pass
        elif self.pid == 3:
            fn_dict = {
                "dilation": dilation,
                "erosion": erosion,
                "opening": opening,
                "closing": closing
            }
            fn = fn_dict[self.choice]
            result_arr = fn(arr, disk(self.option_value))
        elif self.pid == 4:
            thresh = threshold_otsu(arr)
            binary_arr = arr > thresh
            if self.choice == "distance/ostu":
                skel, distance = medial_axis(binary_arr, return_distance=True)
                max_distance = np.max(distance)
                min_distance = np.min(distance)
                result_arr = (distance - min_distance) / (max_distance -
                                                          min_distance) * 255.
            if self.choice == 'skeleton/ostu':
                skel = skeletonize(binary_arr)
                result_arr = skel * 255.
        else:
            result_arr = arr

        result_pil = PIL.Image.fromarray((result_arr).astype(np.uint8))
        return serve_pil(result_pil)
コード例 #29
0
def binary_BF(image,
              meanse=disk(10),
              edgefilt='prewitt',
              opense=disk(10),
              fill_first=False,
              bi_thresh=0.000025,
              tophatse=disk(20)):

    #convertim = img_as_ubyte(image)
    meanim = rank.mean(image, meanse)
    if edgefilt is 'prewitt':
        edgeim = prewitt(meanim)
    elif edgefilt is 'sobel':
        edgeim = sobel(meanim)
    elif edgefilt is 'scharr':
        edgeim = scharr(meanim)
    elif edgefilt is 'roberts':
        edgeim = roberts(meanim)

    closeim = closing(edgeim, opense)
    openim = opening(closeim, opense)
    if fill_first:
        seed = np.copy(openim)
        seed[1:-1, 1:-1] = openim.max()
        mask = openim
        filledim = reconstruction(seed, mask, method='erosion')
        binarim = filledim > bi_thresh
    else:
        binarim = openim > bi_thresh * np.mean(openim)
        seed = np.copy(binarim)
        seed[1:-1, 1:-1] = binarim.max()
        mask = binarim
        filledim = reconstruction(seed, mask, method='erosion')

    tophim = filledim - closing(white_tophat(filledim, tophatse),
                                opense) > 0.01

    fig, ax = plt.subplots(nrows=2, ncols=4, figsize=(16, 8))
    ax[0][0].imshow(image, cmap='gray')
    ax[0][1].imshow(meanim, cmap='gray')
    ax[0][2].imshow(edgeim, cmap='gray', vmax=4 * np.mean(edgeim))
    ax[0][3].imshow(closeim, cmap='gray', vmax=4 * np.mean(closeim))
    ax[1][0].imshow(openim, cmap='gray', vmax=4 * np.mean(openim))
    ax[1][1].imshow(binarim, cmap='gray')
    ax[1][2].imshow(filledim, cmap='gray')
    ax[1][3].imshow(tophim, cmap='gray')
    for axes in ax:
        for axe in axes:
            axe.axis('off')
    fig.tight_layout()

    return tophim
def addEdges(df, gray):
    canny_edges = canny(gray, 0.6)
    roberts_edges = roberts(gray)
    sobel_edges = sobel(gray)
    scharr_edges = scharr(gray)
    prewitt_edges = prewitt(gray)
    df['canny_edges'] = canny_edges.reshape(-1)
    df['roberts_edge'] = roberts_edges.reshape(-1)
    df['sobel_edge'] = sobel_edges.reshape(-1)
    df['scharr_edge'] = scharr_edges.reshape(-1)
    df['prewitt_edge'] = prewitt_edges.reshape(-1)

    return df
コード例 #31
0
 def execute(input_image, settings):
     filter_number = settings.boundaries_settings[0]
     grayscale = input_image.convert('L')
     if filter_number == 1:
         edges = roberts(grayscale)
     elif filter_number == 2:
         edges = prewitt(grayscale)
     elif filter_number == 3:
         edges = scharr(grayscale)
     elif filter_number == 4:
         edges = sobel(grayscale)
     array = np.uint8(plt.cm.gist_earth(edges) * 255)
     return Image.fromarray(array).convert(mode='L')
コード例 #32
0
def loco(D, algorithm='muddy', detail=12, cutoff=0.04):
    """
    Estimate local contrast for the given bitmap. Zero indicates a total
    absence of local intensity variation, and one indicates ultimate contrast.
    With other words, this sounds like a job for a traditional edge detector.

    Parameters
    ----------
    D : greyscale image array
        Desaturated difference with the background.
    algorithm : str, optional
        The method to use. Choose between muddy (home grown, see notes below)
        or one of Scharr / Sobel / Prewitt / Roberts (classics from scikits).
    cutoff : float, optional
        Eualization clipping limit, somewhere in the range 0 - 1.
        Note that a value of 0.1 is already quite agressive.
    detail : int or float, optional
        A measure for the evaluation radius, in pixels.
        Set this to the typical line width or edge gradient width.
        Only relevant for the muddy algorithm.

    Notes
    -----
    This is supposed to yield a map that approximates the intensity difference
    between nearby light and dark zones for all points. Points with high local
    contrast are eligible for serving as morph nodes. Our way of working here:

        1. Normalize contrast through adaptive histogram equalization
        2. Apply the selected algorithm. In case of muddy:
            a) Subtract a Gaussian blur
            b) Take the absolute value of this difference.
    """

    G = desaturate(D, cutoff=cutoff)

    algorithm = algorithm.lower().strip()

    if algorithm == 'muddy':
        F = gaussian_filter(G, sigma=detail)
        C = abs(G - F)

    elif algorithm == 'scharr':
        C = scharr(G)
    elif algorithm == 'sobel':
        C = sobel(G)
    elif algorithm == 'prewitt':
        C = prewitt(G)
    elif algorithm == 'roberts':
        C = roberts(G)

    return C
コード例 #33
0
ファイル: skimage_filters.py プロジェクト: kcavagnolo/ml_fun
io.show()   

##
from skimage.filters import gaussian, gaussian_filter, laplace,prewitt
from skimage.filters import prewitt_v,prewitt_h,scharr, wiener

gauss=gaussian(gray0, sigma=5, multichannel=True)
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)
コード例 #34
0
.. [1] https://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators

.. [2] B. Jaehne, H. Scharr, and S. Koerkel. Principles of filter design. In
       Handbook of Computer Vision and Applications. Academic Press, 1999.

.. [3] https://en.wikipedia.org/wiki/Prewitt_operator
"""

x, y = np.ogrid[:100, :100]
# Rotation-invariant image with different spatial frequencies
img = np.exp(1j * np.hypot(x, y)**1.3 / 20.).real

edge_sobel = sobel(img)
edge_scharr = scharr(img)
edge_prewitt = prewitt(img)

diff_scharr_prewitt = edge_scharr - edge_prewitt
diff_scharr_sobel = edge_scharr - edge_sobel
max_diff = np.max(np.maximum(diff_scharr_prewitt, diff_scharr_sobel))

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

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

ax1.imshow(edge_scharr, cmap=plt.cm.gray)
ax1.set_title('Scharr Edge Detection')
ax1.axis('off')
コード例 #35
0
ファイル: image.py プロジェクト: JorgeDeLosSantos/NanchiPlot
def prewitt(X):
    pw = filters.prewitt(X)
    return pw
コード例 #36
0
import nifty.cgp as ncgp
import nifty.segmentation as nseg

import skimage.data    as sdata
import skimage.filters as sfilt

# plotting
import pylab


# get data
img = sdata.coins()

# edge indicator
edgeIndicator = sfilt.prewitt(sfilt.gaussian(img, 3))

# watersheds
overseg = nseg.seededWatersheds(edgeIndicator, 
        method='node_weighted', acc='min')

f = pylab.figure()
f.add_subplot(2,2,1)
pylab.imshow(img/255)
f.add_subplot(2,2,2)
pylab.imshow(edgeIndicator)
f.add_subplot(2,2,3)
pylab.imshow(overseg, cmap=nseg.randomColormap(overseg.max()+1))
f.add_subplot(2,2,4)
pylab.imshow(nseg.markBoundaries(img, overseg))
pylab.show()
コード例 #37
0
ファイル: test_edges.py プロジェクト: lotteanna/scikit-image
def test_prewitt_mask():
    """Prewitt on a masked array should be zero."""
    np.random.seed(0)
    result = filters.prewitt(np.random.uniform(size=(10, 10)),
                             np.zeros((10, 10), bool))
    assert_allclose(np.abs(result), 0)
コード例 #38
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))
コード例 #39
0
ファイル: initia_sailesh.py プロジェクト: sajal0jain/dsg
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)
edge_scharr = scharr(img_name_gs)
edge_prewitt = prewitt(img_name_gs)

diff_scharr_prewitt = edge_scharr - edge_prewitt
diff_scharr_sobel = edge_scharr - edge_sobel
max_diff = np.max(np.maximum(diff_scharr_prewitt, diff_scharr_sobel))

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

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

ax1.imshow(edge_scharr, cmap=plt.cm.gray)
ax1.set_title('Scharr Edge Detection')
ax1.axis('off')
コード例 #40
0
ファイル: test_edges.py プロジェクト: lotteanna/scikit-image
def test_prewitt_zeros():
    """Prewitt on an array of all zeros."""
    result = filters.prewitt(np.zeros((10, 10)), np.ones((10, 10), bool))
    assert_allclose(result, 0)
コード例 #41
-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