コード例 #1
0
ファイル: tools.py プロジェクト: Trineon/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
コード例 #2
0
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 == "lowpass_gaussian":

        s = float(par)
        filt_data = gaussian_filter(data, sigma=s)

    elif filtType == "highpass_gaussian":

        s = float(par)
        lp_data = gaussian_filter(data, sigma=s)
        filt_data = data - lp_data

    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 ==  "gradient":

    return filt_data
コード例 #3
0
ファイル: test_edges.py プロジェクト: ramosapf/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 = F.roberts(image).astype(bool)
    assert_close(result, expected)
コード例 #4
0
ファイル: test_edges.py プロジェクト: umesh563/scikit-image
def test_roberts_diagonal1():
    """Roberts' on an edge should be a one diagonal"""
    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 = F.roberts(image).astype(bool)
    assert_close(result,expected)
コード例 #5
0
ファイル: Edgedetect.py プロジェクト: mohseniaref/PyRAT
        def filter(self, array, *args, **kwargs):
            shp = array.shape
            array = array.reshape((np.prod(shp[0:-2]),) + shp[-2:]) # reshape to (nch, ny, nx)

            for k, arr in enumerate(np.abs(array)):   # loop over channels
                array[k, ...] = filter.roberts(arr)

            array = array.reshape(shp)  # back to original shape
            return array
コード例 #6
0
ファイル: test_edges.py プロジェクト: umesh563/scikit-image
def test_roberts_diagonal2():
    """Roberts' on an edge should be a other diagonal"""
    diagonal = np.tri(10, 10, 0,dtype=int)
    rev_diagonal = np.rot90(diagonal.transpose(),1)

    image = (rev_diagonal > 0).astype(float)
    expected = ~np.rot90((np.tri(10, 10, -1).astype(bool) | \
                np.tri(10, 10, -2).astype(bool).transpose()),1)
    expected = _mask_filter_result(expected,None)
    result = F.roberts(image).astype(bool)
    assert_close(result,expected)
コード例 #7
0
ファイル: analyze_depth2.py プロジェクト: elmonkey/Python_3D
def getEdges(image):
    """Computes sobel and robers edges on uint8 single channel grayscale image
    input: image, single channel numpy array, uint8, and 0-255 range
    outputs: 
        edge_roberts, single channel numpy array, uint64, and 0-1 range
        edge_sobel,   single channel numpy array, uint64, and 0-1 range"""
    from skimage.filter import roberts, sobel
    edge_roberts = roberts(image)
    edge_sobel = sobel(image)

    #print 'Image info', type(image),           image.shape,      image.dtype,      image.min(),      image.max()
    #print 'Sobel info', type(edge_sobel), edge_sobel.shape, edge_sobel.dtype, edge_sobel.min(), edge_sobel.max()

    # Change the range to 0-255 and the type to uint8 
    edge_sobel = np.uint8(edge_sobel * 255)
    edge_roberts = np.uint8(edge_roberts * 255)
    cv2.imshow('input || sobel || roberts', np.hstack((image, edge_sobel, edge_roberts)))
    # cv2.waitKey(0)
    return edge_roberts, edge_sobel
コード例 #8
0
def getEdges(image):
    """Computes sobel and robers edges on uint8 single channel grayscale image
    input: image, single channel numpy array, uint8, and 0-255 range
    outputs: 
        edge_roberts, single channel numpy array, uint64, and 0-1 range
        edge_sobel,   single channel numpy array, uint64, and 0-1 range"""
    from skimage.filter import roberts, sobel
    edge_roberts = roberts(image)
    edge_sobel = sobel(image)

    #print 'Image info', type(image),           image.shape,      image.dtype,      image.min(),      image.max()
    #print 'Sobel info', type(edge_sobel), edge_sobel.shape, edge_sobel.dtype, edge_sobel.min(), edge_sobel.max()

    # Change the range to 0-255 and the type to uint8
    edge_sobel = np.uint8(edge_sobel * 255)
    edge_roberts = np.uint8(edge_roberts * 255)
    cv2.imshow('input || sobel || roberts',
               np.hstack((image, edge_sobel, edge_roberts)))
    # cv2.waitKey(0)
    return edge_roberts, edge_sobel
コード例 #9
0
def filter_function(img_grey, filt='canny'):
    """
    Grayscales and apply edge detectors to image.
    Returns the flattened filtered image array.
    input: raw image 3d tensor
    output: filtered image
    filters: 'sobel', 'roberts', 'scharr'
    default filter = 'canny'
    """
    # grayscale filters:
    if filt == 'sobel':
        return sobel(img_grey)
    elif filt == 'roberts':
        return roberts(img_grey)
    elif filt == 'canny':
        return canny(img_grey)
    elif filt == 'scharr':
        return scharr(image_grey)
    elif filt == ('canny', 'sobel'):
        return canny(sobel(img_grey))
    else:
        raise Exception('No Such Filter!')
コード例 #10
0
ファイル: filter_spatial.py プロジェクト: mohseniaref/PySAR-1
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 == "lowpass_gaussian":

        s = float(par)
        filt_data = gaussian_filter(data, sigma=s)

    elif filtType == "highpass_gaussian":

        s = float(par)
        lp_data = gaussian_filter(data, sigma=s)
        filt_data = data - lp_data

    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 ==  "gradient":

    return filt_data
コード例 #11
0
ファイル: tests.py プロジェクト: zhuangfangwang/PhDProject
from __future__ import print_function

import matplotlib.pyplot as plt
import numpy as np

import sys
import nrrd
from skimage.segmentation import felzenszwalb, slic, quickshift
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
from skimage import filter

img = img_as_float(nrrd.read(sys.argv[1])[0])

sobel = filter.sobel(img)
roberts = filter.roberts(img)





#segments_fz = felzenszwalb(img, scale=100, sigma=0.5, min_size=50)
#segments_slic = slic(img, n_segments=250, compactness=10, sigma=1)
#segments_quick = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5)

#print("Felzenszwalb's number of segments: %d" % len(np.unique(segments_fz)))
#print("Slic number of segments: %d" % len(np.unique(segments_slic)))
#print("Quickshift number of segments: %d" % len(np.unique(segments_quick)))

#fig, ax = plt.subplots(1, 3)
#fig.set_size_inches(8, 3, forward=True)
コード例 #12
0
ファイル: grabseeds.py プロジェクト: arvin580/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=0.05, indices=False)
        coordinates = peak_local_max(distance, threshold_rel=0.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 * 0.35)) + 1, 50)
        square = img[(y0 - d) : (y0 + d), (x0 - d) : (x0 + 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.0 * 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(0.1, 0.92, "File: {0}".format(latex(filename)), color="g")
    ax4.text(0.1, 0.86, "Label: {0}".format(latex(accession)), color="m")
    yy = 0.8
    fw = must_open(opts.outfile, "w")
    if not opts.noheader:
        print >> fw, Seed.header(calibrate=calib)
    for o in objects:
        if calib:
            o.calibrate(pixel_cm_ratio, tr)
        print >> fw, o
        i = o.seedno
        if i > 7:
            continue
        ax4.text(0.01, yy, str(i), va="center", bbox=dict(fc="none", ec="k"))
        ax4.text(0.1, yy, o.pixeltag, va="center")
        yy -= 0.04
        ax4.add_patch(Rectangle((0.1, yy - 0.025), 0.12, 0.05, lw=0, fc=rgb_to_hex(o.rgb)))
        ax4.text(0.27, yy, o.hashtag, va="center")
        yy -= 0.06
    ax4.text(0.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
コード例 #13
0
ファイル: MAX.py プロジェクト: KamalovMikhail/ResearchNLP
__author__ = 'mikhail'
import numpy as np
from skimage import filter


arr = np.array([[4, 4, 4, 4, 4, 4, 4, 4],
    [3, 2, 1, 2, 1, 2, 1, 3],
    [3, 1, 2, 1, 2, 1, 2, 3],
    [3, 2, 1, 2, 1, 2, 1, 3],
    [3, 1, 2, 1, 2, 1, 2, 3],
    [3, 2, 1, 2, 1, 2, 1, 3],
    [3, 1, 2, 1, 2, 1, 2, 3],
    [4, 4, 4, 4, 4, 4, 4, 4]])

gaussian = filter.gaussian_filter(arr)
roberts = filter.roberts(arr)

print gaussian
print roberts
コード例 #14
0
ファイル: test_edges.py プロジェクト: ramosapf/scikit-image
def test_roberts_zeros():
    """Roberts' filter on an array of all zeros."""
    result = F.roberts(np.zeros((10, 10)), np.ones((10, 10), bool))
    assert (np.all(result == 0))
コード例 #15
0
ファイル: grabseeds.py プロジェクト: shunte88/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)
        square = img[(y0 - d):(y0 + d), (x0 - d):(x0 + 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 >> fw, Seed.header(calibrate=calib)
    for o in objects:
        if calib:
            o.calibrate(pixel_cm_ratio, tr)
        print >> fw, o
        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
コード例 #16
0
import matplotlib.pyplot as plt
from skimage.filter import roberts, sobel

img_col = imread("brain.png")
edge_roberts = roberts(img)
edge_sobel = sobel(img)

#Normalize
edge_roberts = (edge_roberts - edge_roberts.min()) / (edge_roberts.max() -
                                                      edge_roberts.min())
edge_sobel = (edge_sobel - edge_sobel.min()) / (edge_sobel.max() -
                                                edge_sobel.min())

#Clean
edge_roberts *= (edge_roberts > 0.1)
edge_sobel *= (edge_sobel > 0.1)

# Red
brain_red = np.ones_like(img_col)
brain_red[:, :, 1] = 1 - edge_sobel
brain_red[:, :, 2] = 1 - edge_sobel
plt.figure()
imshow(brain_red)

# Black
brain_green = np.ones_like(img_col)
brain_green[:, :, 0] = (1 - edge_sobel)
brain_green[:, :, 1] = (1 - edge_sobel)
brain_green[:, :, 2] = (1 - edge_sobel)
plt.figure()
imshow(brain_green)
コード例 #17
0
def process_image(image):
    img = filter.roberts(image[:, :, 0] / 255.)
    return (255 - img * 255).astype(np.uint8)
コード例 #18
0
ファイル: detect_skin.py プロジェクト: giulio-zhou/FaceFind
def skinDetection(img, show_img=False):
    def visualize(img, show_img):
        if show_img:
            plt.imshow(img, cmap=plt.cm.gray)
            plt.colorbar()
            plt.show()

    gray_img = rgb2gray(img)
    filtered = yCbCr_to_bin(img, 161.9964, -11.1051, 22.9265, 25.9997, \
                                 4.3568, 3.9479, 2)
    filtered = morphology.binary_fill_holes(filtered)
    visualize(filtered, show_img)

    # Remove areas smaller than threshold
    # filtered = morphology.binary_opening(filtered, structure=np.ones( (15, 15) ))
    filtered = remove_small_objects(filtered, 170)
    visualize(filtered, show_img)

    # First erosion
    filtered = morphology.binary_erosion(filtered, np.ones( (6, 6) ))
    visualize(filtered, show_img)

    visualize(gray_img, show_img)

    # Run canny edge detection on gray image
    # edge_img = canny(gray_img)
    edge_img = roberts(gray_img)
    edge_idx = np.where(edge_img > 0.1)
    edge_img = np.zeros(edge_img.shape, dtype=bool)
    edge_img[edge_idx] = True
    visualize(edge_img, show_img)

    # Combine edge detection result and filtered image to create composite
    edge_img = np.invert(edge_img)
    composite = np.logical_and(edge_img, filtered)
    visualize(composite, show_img)

    composite = morphology.binary_erosion(composite)
    visualize(composite, show_img)

    # Fill small holes
    composite = morphology.binary_fill_holes(composite)
    visualize(composite, show_img)

    # composite = morphology.binary_opening(composite, structure=np.ones( (3, 3) ))
    # composite = remove_area(composite, 170)
    composite = remove_small_objects(composite, 170)
    visualize(composite, show_img)

    # Label all connected components
    segments, num_segments = label(composite, background=0, return_num=True)
    
    # Generate square windows to encapsulate regions
    img_windows = []
    for i in range(num_segments): 
        segment_idx = np.where(segments == i)
        box_info = gen_box(segment_idx)
        img_windows.append(box_info)
    
    corners = []
    for box in img_windows:
        (x, y), width = box
        corner = [(x - width//2, y - width//2), (x + width//2, y + width//2)]
        corners.append(corner)

    # Extract interesting image segments from the image
    img_segments = extract_boxes_from_img(img, corners)

    # draw = ImageDraw.Draw(img)
    # for corner in corners:
    #     draw.rectangle(corner) 
    # img = np.asarray(img)
    visualize(img, show_img)
    return img_segments
コード例 #19
0
category = 'boots'
image = data.imread(
    '%s/%s/%s' %
    (store,
     category,
     file_name),
    as_grey=True).astype('int32')
# img= scipy.misc.imread('%s/%s/%s' % (store, category,file_name)).astype('int32')
print file_name
resized_image = resize(image, (250, 250))


# In[8]:


edge_roberts = roberts(resized_image)
edge_roberts_re = roberts(resized_image)
edge_sobel = sobel(image)


fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 7))

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')

コード例 #20
0
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import train_test_split
import os
import matplotlib.pyplot as plt
get_ipython().magic(u'matplotlib inline')

path = '/Users/heymanhn/Virginia/Zipfian/Capstone_Project/Test_Output_Images/boots'
file_name = 'barneys_158585078.jpg'
image = io.imread('%s/%s' % (path, file_name))
plt.imshow(image)
image_grey = color.rgb2gray(image)

# In[58]:

edge_roberts = roberts(image_grey)
edge_canny = canny(image_grey)
edge_sobel = sobel(image_grey)
edge_scharr = scharr(image_grey)

# In[59]:

fig, ((ax0, ax1), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 7))

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

ax1.imshow(edge_canny, cmap=plt.cm.gray)
ax1.set_title('Canny Edge Detection')
ax1.axis('off')
コード例 #21
0
==============
Edge operators
==============

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 matplotlib.pyplot as plt

from skimage.data import camera
from skimage.filter import roberts, sobel


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

fig, (ax0, ax1) = plt.subplots(ncols=2)

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.show()
コード例 #22
0

def preprocessing_center(img, det):
    return im_crop((img / MaximumPixelIntensity)
                   , 6.0)


im_list, det = load_img_det(1000)


im = im_list[1]

im_0_gen = generator_crop_flip_8fold(im_list[1], det, preprocessing_gauss_center_entr)
im_1_gen = generator_crop_flip_8fold(im_list[1], det, preprocessing_gauss_center)

sob = roberts(im)
#edges = preprocessing_center(sob, det)
#edges = filter.canny(im_list[0], sigma=3, low_threshold=0, high_threshold=1000)
# Detect two radii
hough_radii = np.arange(15, 30, 2)
hough_res = hough_circle(sob, hough_radii)

#centers = []
#accums = []
#radii = []
#
#for radius, h in zip(hough_radii, hough_res):
#    # For each radius, extract two circles
#    peaks = peak_local_max(h, num_peaks=2)
#    centers.extend(peaks)
#    accums.extend(h[peaks[:, 0], peaks[:, 1]])