def _plot_default(self):
        # Create a GridContainer to hold all of our plots: 2 rows, 4 columns:
        container = GridContainer(fill_padding=True,
                                  bgcolor="lightgray", use_backbuffer=True,
                                  shape=(2, 4))

        arrangements = [('top left', 'h'),
                        ('top right', 'h'),
                        ('top left', 'v'),
                        ('top right', 'v'),
                        ('bottom left', 'h'),
                        ('bottom right', 'h'),
                        ('bottom left', 'v'),
                        ('bottom right', 'v')]
        orientation_name = {'h': 'horizontal', 'v': 'vertical'}

        pd = ArrayPlotData(image=face())
        # Plot some bessel functions and add the plots to our container
        for origin, orientation in arrangements:
            plot = Plot(pd, default_origin=origin, orientation=orientation)
            plot.img_plot('image')

            # Attach some tools to the plot
            plot.tools.append(PanTool(plot))
            zoom = ZoomTool(plot, tool_mode="box", always_on=False)
            plot.overlays.append(zoom)

            title = '{0}, {1}'
            plot.title = title.format(orientation_name[orientation],
                                      origin.replace(' ', '-'))

            # Add to the grid container
            container.add(plot)

        return container
Ejemplo n.º 2
0
    def setup_method(self, method):
        im = face(gray=True)
        self.ascent_offset = np.array((256, 256))
        s = hs.signals.Signal2D(np.zeros((10, 100, 100)))
        self.scales = np.array((0.1, 0.3))
        self.offsets = np.array((-2, -3))
        izlp = []
        for ax, offset, scale in zip(
                s.axes_manager.signal_axes, self.offsets, self.scales):
            ax.scale = scale
            ax.offset = offset
            izlp.append(ax.value2index(0))
        self.izlp = izlp
        self.ishifts = np.array([(0, 0), (4, 2), (1, 3), (-2, 2), (5, -2),
                                 (2, 2), (5, 6), (-9, -9), (-9, -9), (-6, -9)])
        self.new_offsets = self.offsets - self.ishifts.min(0) * self.scales
        zlp_pos = self.ishifts + self.izlp
        for i in range(10):
            slices = self.ascent_offset - zlp_pos[i, ...]
            s.data[i, ...] = im[slices[0]:slices[0] + 100,
                                slices[1]:slices[1] + 100]
        self.signal = s

        # How image should be after successfull alignment
        smin = self.ishifts.min(0)
        smax = self.ishifts.max(0)
        offsets = self.ascent_offset + self.offsets / self.scales - smin
        size = np.array((100, 100)) - (smax - smin)
        self.aligned = im[int(offsets[0]):int(offsets[0] + size[0]),
                          int(offsets[1]):int(offsets[1] + size[1])]
Ejemplo n.º 3
0
def plotImage( sCells ):

    iSize, jSize = sCells.shape
    sMax = sCells.max()
    print 'The maximum value is: ',sMax

    ima = np.zeros( (iSize, jSize, 3), dtype=np.uint8)
    for i in range(iSize):
        for j in range(jSize):
            val = int( sCells[i][j] / sMax * 255)
            if ((val >= 254) or (val == 0)):
                ima[i][j][0] = 255
            else:
                ima[i][j] = val
            # if sCells[i][j]==sMax:
            #     print i,j

    f = misc.face(gray=True)
    plt.imshow(f)
    plt.title("... !!! ...")
    plt.show()

    plt.imshow(sCells,  cmap=plt.cm.gray )
    plt.title("Raw image (no filter)")
    plt.show()

    plt.imshow(ima)
    plt.title("O and >249 values set to 255 (red)")
    plt.show()
Ejemplo n.º 4
0
def get_image():
    # Build Image
    try:
        filename = sys.argv[1]
        image = ndimage.imread(filename, flatten=True).astype(np.float32)
    except IndexError:
        image = misc.face(gray=True).astype(np.float32)
    return image
Ejemplo n.º 5
0
def process_image_02():
    img = misc.face()
    plt.gray()
    plt.axis('off')  # removes the axis and the ticks
    plt.imshow(img)
    print(img.dtype)
    print(img.shape)
    print(img.max)

    plt.show()
Ejemplo n.º 6
0
def test_connect_regions():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)
    for thr in (50, 150):
        mask = face > thr
        graph = img_to_graph(face, mask)
        assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
Ejemplo n.º 7
0
def test_connect_regions():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)
    for thr in (50, 150):
        mask = face > thr
        graph = img_to_graph(face, mask)
        assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
Ejemplo n.º 8
0
def main():
    args = parse_args()

    if not os.path.exists(args.out_dir):
        os.makedirs(args.out_dir)

    target_layer_names = ['35']
    target_index = None

    # Prepare input image
    if args.img:
        img = cv2.imread(args.img, 1)
    else:
        img = misc.face()
    img = np.float32(cv2.resize(img, (224, 224))) / 255
    preprocessed_img = preprocess_image(img, args.cuda)

    model = vgg19(pretrained=True)
    if args.cuda:
        model.cuda()

    # Prediction
    output = model(preprocessed_img)
    pred_index = np.argmax(output.data.cpu().numpy())
    print('Prediction: {}'.format(IMAGENET_LABELS[pred_index]))

    # Prepare grad cam
    grad_cam = GradCam(pretrained_model=model,
                       target_layer_names=target_layer_names,
                       cuda=args.cuda)

    # Compute grad cam
    mask = grad_cam(preprocessed_img, target_index)

    save_cam_image(img, mask, os.path.join(args.out_dir, 'grad_cam.jpg'))
    print('Saved Grad-CAM image')

    # Reload preprocessed image
    preprocessed_img = preprocess_image(img)

    # Compute guided backpropagation
    guided_backprop = GuidedBackpropGrad(pretrained_model=model,
                                         cuda=args.cuda)
    guided_backprop_saliency = guided_backprop(preprocessed_img,
                                               index=target_index)

    cam_mask = np.zeros(guided_backprop_saliency.shape)
    for i in range(guided_backprop_saliency.shape[0]):
        cam_mask[i, :, :] = mask

    cam_guided_backprop = np.multiply(cam_mask, guided_backprop_saliency)
    save_as_gray_image(cam_guided_backprop,
                       os.path.join(args.out_dir, 'guided_grad_cam.jpg'))
    print('Saved Guided Grad-CAM image')
Ejemplo n.º 9
0
def images_fine_tuning():
    resnet_settings = {'include_top': False, 'weights': 'imagenet'}
    resnet = ResNet50(**resnet_settings)

    img = image.array_to_img(face())
    img = img.resize((224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)

    features = resnet.predict(x)
    print(features)
    def __init__(self, sigma=50):
        """
        Initializer of the object
        """

        self.sigma = sigma
        self.original_image = misc.face(gray=True)
        self.blurred_image = image.gaussian_filter(self.original_image, sigma)

        self.racoon = None
        self.background = None
        self.model = None
Ejemplo n.º 11
0
def scipy_image_manipulation():
    #  Geometrical transformations of an images.

    #  Get a 1024 x 768, color image of a raccoon face. Image used is defalut library image.
    #  raccoon-procyon-lotor.jpg at http://www.public-domain-image.com
    face = misc.face(gray=True)

    # Applying a various transformations

    #  The array is shifted using spline interpolation of the requested order.
    #  Points outside the boundaries of the input are filled according to the given mode.
    shifted_face = ndimage.shift(face, (50, 50))
    shifted_face2 = ndimage.shift(face, (50, 50), mode='nearest')

    #  The array is rotated in the plane defined by the two axes
    #  given by the axes parameter using spline interpolation of the requested order.
    rotated_face = ndimage.rotate(face, 30)

    cropped_face = face[50:-50, 50:-50]  # cropping ndarray
    zoomed_face = ndimage.zoom(
        face, 2
    )  # The array is zoomed using spline interpolation of the requested order.

    print zoomed_face.shape

    #  Createing a new figure.
    plt.figure(figsize=(15, 3))
    #  Adding subplot in current figure.
    plt.subplot(151)
    #  Displaying an image as data on a 2D regular raster in gray color scheme
    plt.imshow(shifted_face, cmap=plt.cm.gray)
    #  Turning off the axis lines and labels.
    plt.axis('off')

    plt.subplot(152)
    plt.imshow(shifted_face2, cmap=plt.cm.gray)
    plt.axis('off')

    plt.subplot(153)
    plt.imshow(rotated_face, cmap=plt.cm.gray)
    plt.axis('off')

    plt.subplot(154)
    plt.imshow(cropped_face, cmap=plt.cm.gray)
    plt.axis('off')

    plt.subplot(155)
    plt.imshow(zoomed_face, cmap=plt.cm.gray)
    plt.axis('off')
    #  adjusting various above defined sub-plots in single frame.
    plt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.99)

    plt.show()
Ejemplo n.º 12
0
def test_keypoints():
    feature_detector = cv2.ORB_create(nfeatures=500,
                                      scaleFactor=1.2,
                                      nlevels=1,
                                      edgeThreshold=31)

    image = misc.face()  # RGB
    image = cv2.resize(image, None, fx=0.5, fy=0.5)
    print('image shape', image.shape)

    keypoints = feature_detector.detect(image[..., ::-1])
    points = [kp.pt for kp in keypoints]
    print('num of keypoints', len(keypoints))

    PRNG = RandomState()

    transform = Compose(
        [
            [ColorJitter(prob=0.75), None],
            Expand((0.8, 1.5)),
            RandomCompose([RandomRotate(360),
                           RandomShift(0.2)]),
            Scale(512),
            # ElasticTransform(300),
            RandomCrop(512),
            HorizontalFlip(),
        ],
        PRNG,
        border='constant',
        fillval=0,
        outside_points='inf')

    results = []

    for _ in range(100):
        img, pts = transform(image, points)

        filtered = []
        for pt in pts:
            x = [abs(pt[0]), abs(pt[1])]
            if np.inf not in x and np.nan not in x:
                filtered.append(pt)

        kps = [cv2.KeyPoint(*pt, 1) for pt in filtered]
        print('num of keypoints', len(kps))

        img = cv2.drawKeypoints(img[..., ::-1], kps, None, flags=0)
        results.append(img[..., ::-1])
        cv2.imshow('keypoints', img)
        c = cv2.waitKey(600)
        if c == 27 or c == ord('q'):  # ESC / 'q'
            break
Ejemplo n.º 13
0
    def draw_circle(frame):
        f = misc.face(gray=True)
        sx, sy = f.shape
        X, Y = np.ogrid[0:sx, 0:sy]

        r = np.hypot(X - sx / 2, Y - sy / 2)
        rbin = (20 * r / r.max()).astype(np.int)
        radial_mean = ndimage.mean(f,
                                   labels=rbin,
                                   index=np.arange(1,
                                                   rbin.max() + 1))
        print(radial_mean.reshape(frame.shape))
        return radial_mean
Ejemplo n.º 14
0
def test_connect_regions():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)
    # subsample by 4 to reduce run time
    face = face[::4, ::4]
    for thr in (50, 150):
        mask = face > thr
        graph = img_to_graph(face, mask)
        assert ndimage.label(mask)[1] == connected_components(graph)[0]
Ejemplo n.º 15
0
def test_access_errors_2d():
    """Test expected access errors for 2d packets."""
    face = misc.face()
    face = np.mean(face, axis=-1).astype(np.float64)

    twp = WaveletPacket2D(None, "haar")
    with pytest.raises(ValueError):
        twp["a"]

    twp.transform(torch.from_numpy(face))

    with pytest.raises(KeyError):
        twp["a" * 100]
Ejemplo n.º 16
0
def image():
    f = misc.face()
    misc.imsave('face.png', f)

    face = misc.imread('face.png')
    print face.shape, face.dtype  # 8-bit images (0-255)

    face.tofile('face.raw')
    face_from_raw = np.fromfile('face.raw', dtype=np.uint8)
    face_from_raw.shape = (768, 1024, 3)

    import matplotlib.pyplot as plt
    plt.imshow(f)  # plt.show()
Ejemplo n.º 17
0
    def initMaps(self,size=49,dim=2,file="data/dice.jpg",timeStop=0.2,constant=0,**kwargs):
        self.timeStop = timeStop
        try:
            im = misc.imread(file)
        except Exception as e:
            print(e)
            im = misc.face()
        im = misc.imresize(im,(size,size))
        gray = to_gray(im)
        value = (gray/255-0.5)*2

        self.input = ConstantMap("picture",size=size,value=value)
        return [self.input]
Ejemplo n.º 18
0
def test_connect_regions_with_grid():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)
    mask = face > 50
    graph = grid_to_graph(*face.shape, mask=mask)
    assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])

    mask = face > 150
    graph = grid_to_graph(*face.shape, mask=mask, dtype=None)
    assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
Ejemplo n.º 19
0
    def test_cli(self):
        f = plt.figure(frameon=False)
        ax = f.add_subplot(111)
        plt.imshow(face(), cmap=plt.cm.gray)
        ax.set_axis_off()
        ax.autoscale_view(True, True, True)
        f.savefig("test.png", bbox_inches='tight')
        plt.close()

        import os
        os.system('magiceye_solver test.png')
        assert os.path.exists("test-solution.png")
        os.remove("test.png")
        os.remove("test-solution.png")
Ejemplo n.º 20
0
def _downsampled_face():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc

        face = misc.face(gray=True)
    face = face.astype(np.float32)
    face = face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2]
    face = face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2]
    face = face.astype(np.float32)
    face /= 16.0
    return face
Ejemplo n.º 21
0
def test_connect_regions_with_grid():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)
    mask = face > 50
    graph = grid_to_graph(*face.shape, mask=mask)
    assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])

    mask = face > 150
    graph = grid_to_graph(*face.shape, mask=mask, dtype=None)
    assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
Ejemplo n.º 22
0
def image():
    f = misc.face()
    misc.imsave("face.png", f)

    face = misc.imread("face.png")
    print face.shape, face.dtype  # 8-bit images (0-255)

    face.tofile("face.raw")
    face_from_raw = np.fromfile("face.raw", dtype=np.uint8)
    face_from_raw.shape = (768, 1024, 3)

    import matplotlib.pyplot as plt

    plt.imshow(f)  # plt.show()
Ejemplo n.º 23
0
def LoadImageData(images, channels=3):
    print("Loading images as RGB"
          if channels == 3 else "Loading Images as GreyScale")
    data = np.array([])
    shapes = [[0, 0]]
    for image in images:
        print(image)
        colorImage = misc.face()
        colorImage = misc.imread(image)
        temp = FlatRGB(colorImage) if channels == 3 else GreyScale(colorImage)
        print temp.shape
        shapes.append(temp.shape)
        data = np.vstack([data, temp]) if data.size else temp
    return data
Ejemplo n.º 24
0
def _downsampled_face():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)
    face = face.astype(np.float32)
    face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2]
            + face[1::2, 1::2])
    face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2]
            + face[1::2, 1::2])
    face = face.astype(np.float32)
    face /= 16.0
    return face
Ejemplo n.º 25
0
def main():

    gray = misc.face(gray=True).astype(np.float32)
    # gray =rgb2gray(imread('test2.jpeg'))
    # gray =rgb2gray(image)
    src1 = resize(gray, (n, n), order=1, preserve_range=True).astype(np.int32)

    plt.imshow(src1, cmap=plt.cm.gray)
    plt.axis('off')
    plt.show()

    histogram = np.zeros(BIN_COUNT, dtype=np.int32)

    # We have threadCount*threadCount per block
    threadsperblock = (threadCount, threadCount)

    blockspergrid_x = math.ceil(src1.shape[0] / threadsperblock[0])
    blockspergrid_y = math.ceil(src1.shape[1] / threadsperblock[1])
    # We have 2*2 blocks
    blockspergrid = (blockspergrid_x, blockspergrid_y)
    print(threadsperblock)
    print(blockspergrid)

    cstream = cuda.stream()  # use stream to trigger async memory transfer
    ts = timer()
    # Increase Counter to measure the Efficiency
    count = 1
    for i in range(count):
        with cstream.auto_synchronize():
            # Copies Data to the device.
            d_src1 = cuda.to_device(src1, stream=cstream)
            # Copies histogram.
            d_hist_src = cuda.to_device(histogram, stream=cstream)
            # call the kernel fucntion
            lbp_texture[blockspergrid, threadsperblock, cstream](d_src1,
                                                                 d_hist_src)

            d_src1.copy_to_host(src1, stream=cstream)
            d_hist_src.copy_to_host(histogram, stream=cstream)

    te = timer()
    print('GPU Process ', count, " Iterations : in ", te - ts)
    print('histogram is')
    print(histogram)

    plt.imshow(src1, cmap=plt.cm.gray)
    plt.axis('off')
    plt.show()
Ejemplo n.º 26
0
 def test_k_mean_face(self):
     face = misc.face(gray=True)
     x = face.reshape((-1, 1))
     k_means = cluster.KMeans(n_clusters=10, n_init=1)
     k_means.fit(x)
     cluster_centers = k_means.cluster_centers_
     values = cluster_centers.squeeze()
     labels = k_means.labels_
     face_compressed = np.choose(labels, values)
     face_compressed.shape = face.shape
     fig = plt.figure()
     ax = fig.add_subplot(121)
     ax.imshow(face)
     ax = fig.add_subplot(122)
     ax.imshow(face_compressed)
     plt.show()
Ejemplo n.º 27
0
def run():

    with st.echo():
        if st.checkbox('Show matplotlib', False):
            import matplotlib.pyplot as plt

            from scipy import misc

            face = misc.face(gray=True)
            plt.imshow(face, cmap='gray')

            st.pyplot()
        else:
            from PIL import Image
            image = Image.open('images/matplotlib.png')
            st.image(image, caption='matplotlib', use_column_width=False)
Ejemplo n.º 28
0
def test_strided_conv_matrix_2d(filter_shape, size, mode):
    """Test strided convolution matrices with full and valid padding."""
    test_filter = torch.rand(filter_shape)
    test_filter = test_filter.unsqueeze(0).unsqueeze(0)
    face = misc.face()[256:(256 + size[0]), 256:(256 + size[1])]
    face = np.mean(face, -1)
    face = torch.from_numpy(face.astype(np.float32))
    face = face.unsqueeze(0).unsqueeze(0)

    if mode == "full":
        padding = (filter_shape[0] - 1, filter_shape[1] - 1)
    elif mode == "valid":
        padding = (0, 0)
    torch_res = torch.nn.functional.conv2d(face,
                                           test_filter.flip(2, 3),
                                           padding=padding,
                                           stride=2).squeeze()

    strided_matrix = construct_strided_conv2d_matrix(test_filter.squeeze(),
                                                     size[0],
                                                     size[1],
                                                     stride=2,
                                                     mode=mode)
    res_flat_stride = torch.sparse.mm(strided_matrix,
                                      face.T.flatten().unsqueeze(-1))

    if mode == "full":
        output_shape = [
            int(np.ceil((filter_shape[1] + size[1] - 1) / 2)),
            int(np.ceil((filter_shape[0] + size[0] - 1) / 2)),
        ]
    elif mode == "valid":
        output_shape = [
            (size[1] - (filter_shape[1])) // 2 + 1,
            (size[0] - (filter_shape[0])) // 2 + 1,
        ]
    res_mm_stride = np.reshape(res_flat_stride, output_shape).T

    diff_torch = np.mean(np.abs(torch_res.numpy() - res_mm_stride.numpy()))
    print(
        str(size).center(8),
        filter_shape,
        mode.center(8),
        "torch-error %2.2e" % diff_torch,
        np.allclose(torch_res.numpy(), res_mm_stride.numpy()),
    )
    assert np.allclose(torch_res.numpy(), res_mm_stride.numpy())
Ejemplo n.º 29
0
def main():
    """
    Author: Cameron Gordon, 42370057
    Performs a test using the scipy raccoon face as an example image.
    Then calls intensity_test, which is then plotted. 
    """
    fig = plt.figure(figsize=(10, 10))
    ax = plt.subplot(1, 2, 1)
    face = misc.face()
    plt.imshow(face)

    image = face  # example image
    intensity_test = tf_rescale_intensity(
        image)  # rescales using the test image
    ax = plt.subplot(1, 2, 2)
    plt.imshow(intensity_test)
    plt.show()
Ejemplo n.º 30
0
    def __init__(self, *args, **kwds):
        super().__init__(*args, **kwds)

        self.set_label("Image Source")
        self.connect("node_func_clicked", self.remove)

        self.img = misc.face()

        f = Figure(figsize=(5, 4), dpi=100)
        self.a = f.add_subplot(111)

        sw = Gtk.ScrolledWindow()
        sw.set_border_width(10)

        self.canvas = FigureCanvas(f)
        sw.add(self.canvas)
        sw.set_size_request(200, 200)

        self.item_add(sw, GtkNodes.NodeSocketIO.DISABLE)
        self.set_child_packing(sw, True, True, 0, Gtk.PackType.START)

        self.draw_image()

        # create local node settings
        sources = ["face", "ascent"]
        self.combobox = Gtk.ComboBoxText()
        self.combobox.set_entry_text_column(0)
        for src in sources:
            self.combobox.append_text(src)
        self.combobox.set_active(0)
        self.combobox.connect("changed", self.change_image)

        # internal node items are type DISABLE
        self.item_add(self.combobox, GtkNodes.NodeSocketIO.DISABLE)

        # create node output socket
        lbl = Gtk.Label.new("Image")
        lbl.set_xalign(1.0)
        self.node_socket_output = self.item_add(lbl,
                                                GtkNodes.NodeSocketIO.SOURCE)
        self.node_socket_output.connect("socket_connect",
                                        self.node_socket_connect)

        # the compatibility key
        self.node_socket_output.set_key(1234)
        self.node_socket_output.set_rgba(get_rgba('darkturquoise'))
Ejemplo n.º 31
0
def framing_lena():
    lena = misc.face()
    plt.imshow(lena, cmap=plt.cm.gray)
    plt.savefig('lena.png')

    crop_lena = lena[30:-30, 30:-30]
    plt.imshow(crop_lena)
    plt.savefig('crop_lena.png')

    y, x = np.ogrid[0:512, 0:512]
    print(y.shape, x.shape)
    centerx, centery = (256, 256)
    mask = (((y - centery)/1.)**2 + ((x - centerx)/0.8)**2) > 230**2
    lena[mask] = 0
    plt.imshow(lena[30:-30, 30:-30], cmap=plt.cm.gray)
    plt.savefig('lena_mask.png')
    return
Ejemplo n.º 32
0
    def _prepareData(self, **kwargs):
        """ 
        This method gets the kwargs passed to the addData() method, and
        stores them for use during this data loading.
        """
        # copy defaults, then update with kwarg options
        opts = copy.deepcopy(self.default_opts)
        opts = self._updateOpts(opts, **kwargs)

        self.dataSource = opts['dataSource']['value']
        self.xrange = list(map(int, opts['xrange']['value']))
        self.yrange = list(map(int, opts['yrange']['value']))
        self.stepsize = int(opts['stepsize']['value'])
        self.framesize = int(opts['framesize']['value'])
        self.doFourier = opts['fourier']['value']

        self.image = face(gray=True)
Ejemplo n.º 33
0
def main( model_path ):
    # network構造定義に必要なパラメータ
    num_channel     = 1
    gene_dim_hidden = 200
    disc_dropout_rate   = 0.25
    hyper_param = Hyper_Param_pix2pixGAN(
            model_path          = model_path, 
            num_channel         = num_channel,
            gene_dim_hidden     = gene_dim_hidden,
            disc_dropout_rate   = disc_dropout_rate
    )

    engine = Engine_pix2pixGAN()
    engine.load(hyper_param)

    dataset = Dataset_mnist()
    dataset.load()    # download mnist data
    dataset.x_train = np.reshape( dataset.x_train, dataset.x_train.shape + (1,) ) / 255.0
    
    from scipy import misc
    face = misc.face(gray=True)
    x_train_blur = np.zeros( dataset.x_train.shape )
    for i in range(dataset.x_train.shape[0]):
        x_train_blur[i, :, :, 0] = ndimage.gaussian_filter(dataset.x_train[i, :, :, 0], sigma=1.5)

    print('exec prediction')
    # prediction
    w = 10
    h = 10
    generated_image = engine.predict( x_train_blur[:(w*h), :, :, :], mode='generator' )
    prob            = engine.predict( x_train_blur[:(w*h), :, :, :], mode='discriminator' )

    print("Discriminator: prob =", prob.data)

    dir ='./predict'
    if os.path.exists(dir) is False:
        os.makedirs(dir)

    img = tile_image(generated_image.data, w=w, h=h)
    pil = Image.fromarray( np.uint8( img * 255 ) )
    pil.save( dir + 'pix2pixgan_generated.tif')

    img = tile_image(x_train_blur.data, w=w, h=h)
    pil = Image.fromarray( np.uint8( img * 255 ) )
    pil.save( dir + 'pix2pixgan_input.tif')
Ejemplo n.º 34
0
def test_connect_regions_with_grid():
    try:
        face = sp.face(gray=True)
    except AttributeError:
        # Newer versions of scipy have face in misc
        from scipy import misc
        face = misc.face(gray=True)

    # subsample by 4 to reduce run time
    face = face[::4, ::4]

    mask = face > 50
    graph = grid_to_graph(*face.shape, mask=mask)
    assert ndimage.label(mask)[1] == connected_components(graph)[0]

    mask = face > 150
    graph = grid_to_graph(*face.shape, mask=mask, dtype=None)
    assert ndimage.label(mask)[1] == connected_components(graph)[0]
Ejemplo n.º 35
0
    def setUp(self):
        super(TestImageLoader, self).setUp()
        from PIL import Image
        self.current_dir = os.path.dirname(os.path.abspath(__file__))
        self.tif_image_path = os.path.join(self.current_dir, "a_image.tif")

        # Create image file
        self.data_dir = tempfile.mkdtemp()
        self.face = misc.face()
        self.face_path = os.path.join(self.data_dir, "face.png")
        Image.fromarray(self.face).save(self.face_path)
        self.face_copy_path = os.path.join(self.data_dir, "face_copy.png")
        Image.fromarray(self.face).save(self.face_copy_path)

        # Create zip of image file
        #self.zip_path = "/home/rbharath/misc/cells.zip"
        self.zip_path = os.path.join(self.data_dir, "face.zip")
        zipf = zipfile.ZipFile(self.zip_path, "w", zipfile.ZIP_DEFLATED)
        zipf.write(self.face_path)
        zipf.close()

        # Create zip of multiple image files
        self.multi_zip_path = os.path.join(self.data_dir, "multi_face.zip")
        zipf = zipfile.ZipFile(self.multi_zip_path, "w", zipfile.ZIP_DEFLATED)
        zipf.write(self.face_path)
        zipf.write(self.face_copy_path)
        zipf.close()

        # Create zip of multiple image files, multiple_types
        self.multitype_zip_path = os.path.join(self.data_dir,
                                               "multitype_face.zip")
        zipf = zipfile.ZipFile(self.multitype_zip_path, "w",
                               zipfile.ZIP_DEFLATED)
        zipf.write(self.face_path)
        zipf.write(self.tif_image_path)
        zipf.close()

        # Create image directory
        self.image_dir = tempfile.mkdtemp()
        face_path = os.path.join(self.image_dir, "face.png")
        Image.fromarray(self.face).save(face_path)
        face_copy_path = os.path.join(self.image_dir, "face_copy.png")
        Image.fromarray(self.face).save(face_copy_path)
Ejemplo n.º 36
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        arr = np.array([2,3,4])
        s = pd.Series([1, 3, 5, np.nan, 6, 8])
        face = misc.face()

        clf = RandomForestClassifier(random_state=0)
        X = [[ 1,  2,  3], [11, 12, 13]]
        y = [0, 1]
        clf.fit(X, y)
        preX = clf.predict(X) 
        pre4 = clf.predict([[4, 5, 6], [14, 15, 16]])

        mnist = tf.keras.datasets.mnist

        (x_train, y_train), (x_test, y_test) = mnist.load_data()
        x_train, x_test = x_train / 255.0, x_test / 255.0
        model = tf.keras.models.Sequential([
        tf.keras.layers.Flatten(input_shape=(28, 28)),
        tf.keras.layers.Dense(128, activation='relu'),
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(10)
        ])
        predictions = model(x_train[:1]).numpy()

        return func.HttpResponse(f"HelloMac, {name}. numpy={arr}. pandas={s}. scipy={face} scikit={preX}{pre4}. tensorflow={predictions}.")
 
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )
Ejemplo n.º 37
0
 def __init__(self):
     self.dimenciones = 2
     self.imagen = misc.face()
     self.y = np.vsplit(self.imagen, self.dimenciones)
     self.v = []
     self.posicion_valor = [self.dimenciones - 1, self.dimenciones - 1]
     for i in range(self.dimenciones):
         self.v.append(np.hsplit(self.y[i], self.dimenciones))
     self.imagen_original = np.array(self.v)
     self.imagen_piezas = self.imagen_original.copy()
     self.imagen_piezas[self.dimenciones - 1,
                        self.dimenciones - 1, :, :, :] = np.zeros_like(
                            self.imagen_piezas[self.dimenciones - 1,
                                               self.dimenciones -
                                               1, :, :, :])
     self.imagen_original = np.copy(self.imagen_piezas)
     self.imagen_auxiliar = np.zeros_like(self.imagen_original)
     self.armar_puzzle()
     self.imprimir_puzzle()
     self.ejecutar_puzzle()
def _compare_trees2(
    wavelet_str: str,
    max_lev: int,
    pywt_boundary: str = "zero",
    ptwt_boundary: str = "zero",
    height: int = 256,
    width: int = 256,
    batch_size: int = 1,
):

    face = misc.face()[:height, :width]
    face = np.mean(face, axis=-1).astype(np.float64)
    wavelet = pywt.Wavelet(wavelet_str)
    batch_list = []
    for _ in range(batch_size):
        wp_tree = pywt.WaveletPacket2D(
            data=face,
            wavelet=wavelet,
            mode=pywt_boundary,
        )
        # Get the full decomposition
        wp_keys = list(product(["a", "h", "v", "d"], repeat=max_lev))
        np_packets = []
        for node in wp_keys:
            np_packet = wp_tree["".join(node)].data
            np_packets.append(np_packet)
        np_packets = np.stack(np_packets, 0)
        batch_list.append(np_packets)
    batch_np_packets = np.stack(batch_list, 0)

    # get the PyTorch decomposition
    pt_data = torch.stack([torch.from_numpy(face)] * batch_size, 0)
    ptwt_wp_tree = WaveletPacket2D(pt_data,
                                   wavelet=wavelet,
                                   mode=ptwt_boundary)
    packets = []
    for node in wp_keys:
        packet = ptwt_wp_tree["".join(node)]
        packets.append(packet)
    packets_pt = torch.stack(packets, 1).numpy()
    assert np.allclose(packets_pt, batch_np_packets)
Ejemplo n.º 39
0
  def setUp(self):
    super(TestImageLoader, self).setUp()
    self.current_dir = os.path.dirname(os.path.abspath(__file__))
    self.tif_image_path = os.path.join(self.current_dir, "a_image.tif")

    # Create image file
    self.data_dir = tempfile.mkdtemp()
    self.face = misc.face()
    self.face_path = os.path.join(self.data_dir, "face.png")
    misc.imsave(self.face_path, self.face)
    self.face_copy_path = os.path.join(self.data_dir, "face_copy.png")
    misc.imsave(self.face_copy_path, self.face)

    # Create zip of image file
    #self.zip_path = "/home/rbharath/misc/cells.zip"
    self.zip_path = os.path.join(self.data_dir, "face.zip")
    zipf = zipfile.ZipFile(self.zip_path, "w", zipfile.ZIP_DEFLATED)
    zipf.write(self.face_path)
    zipf.close()

    # Create zip of multiple image files
    self.multi_zip_path = os.path.join(self.data_dir, "multi_face.zip")
    zipf = zipfile.ZipFile(self.multi_zip_path, "w", zipfile.ZIP_DEFLATED)
    zipf.write(self.face_path)
    zipf.write(self.face_copy_path)
    zipf.close()

    # Create zip of multiple image files, multiple_types
    self.multitype_zip_path = os.path.join(self.data_dir, "multitype_face.zip")
    zipf = zipfile.ZipFile(self.multitype_zip_path, "w", zipfile.ZIP_DEFLATED)
    zipf.write(self.face_path)
    zipf.write(self.tif_image_path)
    zipf.close()

    # Create image directory
    self.image_dir = tempfile.mkdtemp()
    face_path = os.path.join(self.image_dir, "face.png")
    misc.imsave(face_path, self.face)
    face_copy_path = os.path.join(self.image_dir, "face_copy.png")
    misc.imsave(face_copy_path, self.face)
Ejemplo n.º 40
0
def main():
    # image to be used
    file_img_name = 'lines.jpg'

    f = misc.face()
    f = misc.imread(file_img_name)

    img = cv2.imread(file_img_name, 0)

    edges = cv2.Canny(img, 100, 200)

    whites = get_white_points(edges)

    # Parameters
    # p - probability that one random sample is free from outliers
    p = 0.95
    # e - inlier ratio
    e = 0.5
    S = 5
    #N = abs(int(math.log(1 - p) / math.log(1-math.pow(1-e, S))))
    N = 60

    t = 1
    d = 100

    points, lines = ransac(whites, N, S, t, d)
    f = draw_lines(f, points, lines)

    plt.imshow(f)
    plt.show()

    #gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    plt.subplot(121), plt.imshow(img)
    #plt.subplot(121),plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    plt.title('Original Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122), plt.imshow(edges, cmap='gray')
    plt.title('Edge Image'), plt.xticks([]), plt.yticks([])

    plt.show()
Ejemplo n.º 41
0
def test_random_transform_2d():

    img = face()

    x = dv.AugmentationParameters(
        image_dimension=2,
        translation_range=0.1,
        rotation_range=15,
        scale_range=0.1,
        flip=False,
        fill_mode="constant",
        cval=0.0,
    )

    txf = dv.generate_random_transform(x, img.shape)
    txf = dv.transform_full_matrix_offset_center(txf, img.shape[:-1])

    plt.imshow(
        dv.apply_affine_transform_channelwise(img,
                                              txf[:-1, :],
                                              channel_index=2))
    plt.show()
Ejemplo n.º 42
0
def mandelbrot(size=1500, limits=0, n=100, img=misc.face()):

    width = size
    height = size
    # height=round(width/1.5)

    matrix = np.ndarray(shape=(width, height, 3), dtype=int)

    if limits == 0:
        limits = [-2.0, 0.5, -1.25, 1.25]  #defining limits if not defined

    p = len(img[:, 1])
    q = len(img[1, :])

    for x, re in enumerate(np.linspace(limits[0], limits[1], width)):
        for y, im in enumerate(np.linspace(limits[2], limits[3], height)):
            c = complex(re, im)
            z = 0.0j

            for i in range(round(n)):

                z = z * z + c

                if abs(z) > 25:
                    x2 = np.int(
                        np.floor(
                            p * np.mod(np.real(np.log(np.log(z) * q / p)), 1) /
                            2))
                    y2 = np.int(
                        np.floor((q * np.mod(2 * np.angle(c), 1) + 2) / 2))

                    # matrix[x,y]=x2+y2+(i+x2+y2)/(i+1) #style colorful .. with cmap
                    color = img[x2, y2]

                    matrix[x, y] = color

                    break

    return matrix
Ejemplo n.º 43
0
def main():
   drone = ps_drone.Drone()
   drone.reset()
   i=0
   
   


   while (True):
       cap = misc.face()
       
           
       number=validation.classify("test/snapshot_iter_21120.caffemodel", "test/deploy.prototxt", cap, 
        "test/mean.binaryproto", "test/labels.txt")
        
       print number 
            
       time.sleep(0.5)  

       i=i+1
    
       if i>10:
           exit()
#!/usr/bin/env python

try:
    from scipy.misc import face
    img = face()[:, :, ::-1]
except ImportError:
    from scipy.misc import lena
    img = lena()[:, :, None].repeat(3, axis=2)

import cv_bridge
import rospy
from sensor_msgs.msg import Image


def timer_cb(event):
    imgmsg.header.stamp = rospy.Time.now()
    pub_img.publish(imgmsg)


if __name__ == '__main__':
    rospy.init_node('static_image_publisher')

    pub_img = rospy.Publisher('~output', Image, queue_size=1)

    bridge = cv_bridge.CvBridge()
    imgmsg = bridge.cv2_to_imgmsg(img, encoding='bgr8')

    rospy.Timer(rospy.Duration(0.1), timer_cb)
    rospy.spin()
# -*- coding: utf-8 -*-
"""Linear_fourier_filter_exercise.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1KQlihNHOyF1_p6he0IWGrdA23wIfoUvA
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import ascent, face

# Change this to an image of your choosing!
#image = ascent()  # Boring staircase
image = face().mean(axis=2) # Cute little friend face


image = (image - image.mean()) / image.std()
n_x, n_y = image.shape

plt.imshow(image, cmap='Greys_r')

from numpy.fft import fft2, ifft2, fftshift

image_ft = fftshift(fft2(image))
amp = image_ft.real
phase = np.arctan2(image_ft.imag, image_ft.real)

X,Y = np.meshgrid( np.linspace(-.5, .5, n_y), np.linspace(-.5,.5, n_x) )
k = (X**2 + Y**2)**.5
Ejemplo n.º 46
0
nyq = np.max(row_freq) 

row_freq = np.broadcast_to(np.expand_dims(row_freq,1), 
                           (len(row_freq), len(col_freq)))
col_freq = np.broadcast_to(np.expand_dims(col_freq, 0), 
                           (len(row_freq), len(col_freq)))
mag = (row_freq**2 + col_freq**2)**0.5

def myGuassian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

filt = myGuassian(mag, 25, 10)

#plt.imshow(filt)
from scipy import misc
im = face = misc.face()
im = im[:n,:n, :]/255.
im = np.mean(im, -1)
im= 1-im
plt.imshow(im, cmap='Greys')
n_bin_edges = 10
#fewest_freqs = 10.
#highest_divisor = np.floor(nyq / fewest_freqs)
#bin_edges = nyq/np.logspace(1, np.log2(highest_divisor), num=n_bin_edges, base=2)
#need to work on hwo to do spacing a little bit
bin_upper_edges = nyq/np.geomspace(1, n/10., num=n_bin_edges)
bin_edges = np.append(bin_upper_edges, 0)
bin_half_width = np.abs(np.diff(bin_edges)/2)
bin_centers = [(bin_edges[i+1] + bin_edges[i]) / 2. for i in range(len(bin_edges))[:-1]]
nyq = np.ceil((n/2.)/(bin_centers+bin_half_width*2))
Ejemplo n.º 47
0
 def setUp(self):
     self.image = testdata.prepare_image()
     self.image_wo_exif = Image.fromarray(misc.face())
Ejemplo n.º 48
0
## dic14-im02.py : importing and displaying py predefined images
## SXD 520
import pylab
from scipy import misc

# Synonyms
show = pylab.show()
load = pylab.imshow
Ascent = misc.ascent()
Lena = misc.lena()
Face = misc.face('L')
gray = pylab.gray()  

im = Ascent


load(im,cmap=gray)

show
Ejemplo n.º 49
0
        w = min(W,dx)
        image(temppath,imgx,imgy,width=w)
        imgy = imgy + dy + 20
        os.remove(temppath)
        size(W, HEIGHT+dy+40)
else:
    def pltshow(mplpyplot):
        mplpyplot.show()
# nodebox section end


# #############################################################################
# Generate data
try:  # SciPy >= 0.16 have face in misc
    from scipy.misc import face
    face = face(gray=True)
except ImportError:
    face = sp.face(gray=True)

# Resize it to 10% of the original size to speed up the processing
face = sp.misc.imresize(face, 0.10) / 255.

X = np.reshape(face, (-1, 1))

# #############################################################################
# Define the structure A of the data. Pixels connected to their neighbors.
connectivity = grid_to_graph(*face.shape)

# #############################################################################
# Compute clustering
print("Compute structured hierarchical clustering...")
Ejemplo n.º 50
0
def test_face():
    assert_equal(face().shape, (768, 1024, 3))
Ejemplo n.º 51
0
from scipy import misc

img = misc.face()

print(type(img))
Ejemplo n.º 52
0
low-pass filter which damps out frequencies which are higher than the 
user specified cutoff frequency.  In this example the cutoff frequency 
is set to 40.
'''
import numpy as np
from scipy.misc import face
from scipy.interpolate import NearestNDInterpolator
import matplotlib.pyplot as plt
from rbf.filter import filter
np.random.seed(4)

x = np.linspace(0.0,1.0,768)
y = np.linspace(1.0,0.0,768)
x,y = np.meshgrid(x,y)
points = np.array([x.flatten(),y.flatten()]).T
values = np.linalg.norm(face(),axis=2)[:,256:].flatten()
#values = lena().flatten().astype(float)
values /= 441.7 # normalize so that the max is 1.0
signal = NearestNDInterpolator(points,values)

# interpolate Lena onto new observation points and add noise
points_obs = np.random.normal(0.5,0.3,(100000,2))
#points_obs = rbf.halton.halton(50000,2)  
u_obs = signal(points_obs) + np.random.normal(0.0,0.2,100000)
# find filtered solution
cutoff = 60.0
soln,_ = filter(points_obs,u_obs,cutoff=cutoff,n=20,samples=0)

# plot the observed and filtered results
fig,ax = plt.subplots(2,1,figsize=(6,10))
ax[0].set_aspect('equal')
Ejemplo n.º 53
0
def main():
    # Build Filter
    laplacian_pts = """
    -4 -1 0 -1 -4
    -1 2 3 2 -1
    0 3 4 3 0
    -1 2 3 2 -1
    -4 -1 0 -1 -4
    """.split()

    laplacian = np.array(laplacian_pts, dtype=np.float32).reshape(5, 5)

    # Build Image
    try:
        filename = sys.argv[1]
        image = ndimage.imread(filename, flatten=True).astype(np.float32)
    except IndexError:
        image = misc.face(gray=True).astype(np.float32)

    print("Image size: %s" % (image.shape,))

    response = np.zeros_like(image)
    response[:5, :5] = laplacian

    # CPU
    ts = timer()
    cvimage_cpu = fftconvolve(image, laplacian, mode="same")
    te = timer()
    print("CPU: %.2fs" % (te - ts))

    # GPU
    threadperblock = 32, 8
    blockpergrid = best_grid_size(tuple(reversed(image.shape)), threadperblock)
    print("kernel config: %s x %s" % (blockpergrid, threadperblock))

    # Trigger initialization the cuFFT system.
    # This takes significant time for small dataset.
    # We should not be including the time wasted here
    FFTPlan(shape=image.shape, itype=np.complex64, otype=np.complex64)

    # Start GPU timer
    ts = timer()
    image_complex = image.astype(np.complex64)
    response_complex = response.astype(np.complex64)

    d_image_complex = cuda.to_device(image_complex)
    d_response_complex = cuda.to_device(response_complex)

    fft_inplace(d_image_complex)
    fft_inplace(d_response_complex)

    vmult(d_image_complex, d_response_complex, out=d_image_complex)

    ifft_inplace(d_image_complex)

    cvimage_gpu = d_image_complex.copy_to_host().real / np.prod(image.shape)

    te = timer()
    print("GPU: %.2fs" % (te - ts))

    # Plot the results
    plt.subplot(1, 2, 1)
    plt.title("CPU")
    plt.imshow(cvimage_cpu, cmap=plt.cm.gray)
    plt.axis("off")

    plt.subplot(1, 2, 2)
    plt.title("GPU")
    plt.imshow(cvimage_gpu, cmap=plt.cm.gray)
    plt.axis("off")

    plt.show()
Ejemplo n.º 54
0
#!/usr/bin/env python

"""
Demonstrate matplotlib image operations

Copyright 2018 Zihan Chen
"""


import matplotlib.pyplot as plt
from scipy.misc import face


plt.close('all')
fig, (ax1, ax2) = plt.subplots(2,1)

# read image
img = plt.imread('mpl_basics.jpg')
ax1.imshow(img)

# gray scale images
img_gray = face(gray=True)
ax2.imshow(img_gray, cmap=plt.cm.bone)

# show images
plt.show()
import numpy as np
import scipy as sp
from scipy.ndimage.filters import gaussian_filter
import matplotlib.pyplot as plt
from skimage import img_as_float
from skimage.transform import rescale

from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering


# load the raccoon face as a numpy array
try:  # SciPy >= 0.16 have face in misc
    from scipy.misc import face
    orig_face = img_as_float(face(gray=True))
except ImportError:
    orig_face = img_as_float(sp.face(gray=True))

# Resize it to 10% of the original size to speed up the processing
# Applying a Gaussian filter for smoothing prior to down-scaling
# reduces aliasing artifacts.
smoothened_face = gaussian_filter(orig_face, sigma=4.5)
rescaled_face = rescale(smoothened_face, 0.1, mode="reflect")

# Convert the image into a graph with the value of the gradient on the
# edges.
graph = image.img_to_graph(rescaled_face)

# Take a decreasing function of the gradient: an exponential
# The smaller beta is, the more independent the segmentation is of the
Ejemplo n.º 56
0
from scipy import misc

# Writing an array to a file
f = misc.face() # f.shape = (768, 1024, 3)
misc.imsave('../Assets/face.png', f)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()

# Creating a numpy array from an image file
face = misc.imread('../Assets/face.png')
type(face)
face.shape, face.dtype  # dtype is uint8 for 8-bit images

import numpy as np
# Opening raw files (camera, 3-D images)
face.tofile('../Assets/face.raw')
face_from_raw = np.fromfile('../Assets/face.raw', dtype=np.uint8)   # shape (2359296,)
face_from_raw.shape
face_from_raw.shape = (768, 1024, 3)
# use np.memmap for memory mapping
face_memmap = np.memmap('../Assets/face.raw', dtype=np.uint8, shape=(768, 1024, 3))

# Working on a list of image files
for i in range(10):
    im = np.random.randint(0, 255+1, 10000).reshape((100, 100))
    im.max()
    misc.imsave('../Assets/random_%02d.png' % i, im)
from glob import glob
filelist = glob('../Assets/random*.png')
Ejemplo n.º 57
0
"""
Displaying a Racoon Face
========================

Small example to plot a racoon face.
"""

from scipy import misc
f = misc.face()
misc.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
from sklearn.cluster import spectral_clustering
from sklearn.utils.testing import SkipTest
from sklearn.utils.fixes import sp_version

if sp_version < (0, 12):
    raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and "
                   "thus does not include the scipy.misc.face() image.")


# load the raccoon face as a numpy array
try:
    face = sp.face(gray=True)
except AttributeError:
    # Newer versions of scipy have face in misc
    from scipy import misc
    face = misc.face(gray=True)

# Resize it to 10% of the original size to speed up the processing
face = sp.misc.imresize(face, 0.10) / 255.

# Convert the image into a graph with the value of the gradient on the
# edges.
graph = image.img_to_graph(face)

# Take a decreasing function of the gradient: an exponential
# The smaller beta is, the more independent the segmentation is of the
# actual image. For beta=1, the segmentation is close to a voronoi
beta = 5
eps = 1e-6
graph.data = np.exp(-beta * graph.data / graph.data.std()) + eps
Ejemplo n.º 59
0
def main():
    # Build Filter
    laplacian_pts = '''
    -4 -1 0 -1 -4
    -1 2 3 2 -1
    0 3 4 3 0
    -1 2 3 2 -1
    -4 -1 0 -1 -4
    '''.split()

    laplacian = np.array(laplacian_pts, dtype=np.float32).reshape(5, 5)

    # Build Image
    try:
        filename = sys.argv[1]
        image = ndimage.imread(filename, flatten=True).astype(np.float32)
    except IndexError:
        image = misc.face(gray=True).astype(np.float32)

    print("Image size: %s" % (image.shape,))

    response = np.zeros_like(image)
    response[:5, :5] = laplacian

    # CPU
    ts = timer()
    cvimage_cpu = fftconvolve(image, laplacian, mode='same')
    te = timer()
    print('CPU: %.2fs' % (te - ts))

    # GPU
    threadperblock = 32, 8
    blockpergrid = best_grid_size(tuple(reversed(image.shape)), threadperblock)
    print('kernel config: %s x %s' % (blockpergrid, threadperblock))

    # Trigger initialization the cuFFT system.
    # This takes significant time for small dataset.
    # We should not be including the time wasted here
    FFTPlan(shape=image.shape, itype=np.complex64, otype=np.complex64)

    # Start GPU timer
    ts = timer()
    image_complex = image.astype(np.complex64)
    response_complex = response.astype(np.complex64)

    stream1 = cuda.stream()
    stream2 = cuda.stream()

    fftplan1 = FFTPlan(shape=image.shape, itype=np.complex64,
                       otype=np.complex64, stream=stream1)
    fftplan2 = FFTPlan(shape=image.shape, itype=np.complex64,
                       otype=np.complex64, stream=stream2)

    # pagelock memory
    with cuda.pinned(image_complex, response_complex):

        # We can overlap the transfer of response_complex with the forward FFT
        # on image_complex.
        d_image_complex = cuda.to_device(image_complex, stream=stream1)
        d_response_complex = cuda.to_device(response_complex, stream=stream2)

        fftplan1.forward(d_image_complex, out=d_image_complex)
        fftplan2.forward(d_response_complex, out=d_response_complex)

        stream2.synchronize()

        mult_inplace[blockpergrid, threadperblock, stream1](d_image_complex,
                                                            d_response_complex)
        fftplan1.inverse(d_image_complex, out=d_image_complex)

        # implicitly synchronizes the streams
        cvimage_gpu = d_image_complex.copy_to_host().real / np.prod(image.shape)

    te = timer()
    print('GPU: %.2fs' % (te - ts))

    # Plot the results
    plt.subplot(1, 2, 1)
    plt.title('CPU')
    plt.imshow(cvimage_cpu, cmap=plt.cm.gray)
    plt.axis('off')

    plt.subplot(1, 2, 2)
    plt.title('GPU')
    plt.imshow(cvimage_gpu, cmap=plt.cm.gray)
    plt.axis('off')

    plt.show()