Exemple #1
0
def test_circle_perimeter_aa():
    img = np.zeros((15, 15), 'uint8')
    rr, cc, val = circle_perimeter_aa(7, 7, 0)
    img[rr, cc] = 1
    assert (np.sum(img) == 1)
    assert (img[7][7] == 1)

    img = np.zeros((17, 17), 'uint8')
    rr, cc, val = circle_perimeter_aa(8, 8, 7)
    img[rr, cc] = val * 255
    img_ = np.array(
        [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 82, 180, 236, 255, 236, 180, 82, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 189, 172, 74, 18, 0, 18, 74, 172, 189, 0, 0, 0, 0],
         [0, 0, 0, 229, 25, 0, 0, 0, 0, 0, 0, 0, 25, 229, 0, 0, 0],
         [0, 0, 189, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 189, 0, 0],
         [0, 82, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 172, 82, 0],
         [0, 180, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 180, 0],
         [0, 236, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 236, 0],
         [0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0],
         [0, 236, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 236, 0],
         [0, 180, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 180, 0],
         [0, 82, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 172, 82, 0],
         [0, 0, 189, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 189, 0, 0],
         [0, 0, 0, 229, 25, 0, 0, 0, 0, 0, 0, 0, 25, 229, 0, 0, 0],
         [0, 0, 0, 0, 189, 172, 74, 18, 0, 18, 74, 172, 189, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 82, 180, 236, 255, 236, 180, 82, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    assert_array_equal(img, img_)
Exemple #2
0
def test_circle_perimeter_aa():
    img = np.zeros((15, 15), 'uint8')
    rr, cc, val = circle_perimeter_aa(7, 7, 0)
    img[rr, cc] = 1
    assert(np.sum(img) == 1)
    assert(img[7][7] == 1)

    img = np.zeros((17, 17), 'uint8')
    rr, cc, val = circle_perimeter_aa(8, 8, 7)
    img[rr, cc] = val * 255
    img_ = np.array(
        [[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
         [  0,   0,   0,   0,   0,  82, 180, 236, 255, 236, 180,  82,   0,   0,   0,   0,   0],
         [  0,   0,   0,   0, 189, 172,  74,  18,   0,  18,  74, 172, 189,   0,   0,   0,   0],
         [  0,   0,   0, 229,  25,   0,   0,   0,   0,   0,   0,   0,  25, 229,   0,   0,   0],
         [  0,   0, 189,  25,   0,   0,   0,   0,   0,   0,   0,   0,   0,  25, 189,   0,   0],
         [  0,  82, 172,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 172,  82,   0],
         [  0, 180,  74,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  74, 180,   0],
         [  0, 236,  18,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  18, 236,   0],
         [  0, 255,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255,   0],
         [  0, 236,  18,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  18, 236,   0],
         [  0, 180,  74,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  74, 180,   0],
         [  0,  82, 172,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 172,  82,   0],
         [  0,   0, 189,  25,   0,   0,   0,   0,   0,   0,   0,   0,   0,  25, 189,   0,   0],
         [  0,   0,   0, 229,  25,   0,   0,   0,   0,   0,   0,   0,  25, 229,   0,   0,   0],
         [  0,   0,   0,   0, 189, 172,  74,  18,   0,  18,  74, 172, 189,   0,   0,   0,   0],
         [  0,   0,   0,   0,   0,  82, 180, 236, 255, 236, 180,  82,   0,   0,   0,   0,   0],
         [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0]]
        )
    assert_array_equal(img, img_)
Exemple #3
0
def test_circle_perimeter_aa_shape():
    img = np.zeros((15, 20), 'uint8')
    rr, cc, val = circle_perimeter_aa(7, 10, 9, shape=(15, 20))
    img[rr, cc] = val * 255
    shift = 5
    img_ = np.zeros((15 + 2 * shift, 20), 'uint8')
    rr, cc, val = circle_perimeter_aa(7 + shift, 10, 9, shape=None)
    img_[rr, cc] = val * 255
    assert_array_equal(img, img_[shift:-shift, :])
Exemple #4
0
def test_circle_perimeter_aa_shape():
    img = np.zeros((15, 20), 'uint8')
    rr, cc, val = circle_perimeter_aa(7, 10, 9, shape=(15, 20))
    img[rr, cc] = val * 255
    shift = 5
    img_ = np.zeros((15 + 2 * shift, 20), 'uint8')
    rr, cc, val = circle_perimeter_aa(7 + shift, 10, 9, shape=None)
    img_[rr, cc] = val * 255
    assert_array_equal(img, img_[shift:-shift, :])
Exemple #5
0
 def circle(im, center_border=4, min_radius=4):
     """a circle, may be clipped"""
     rr, cc, vals = circle_perimeter_aa(inset(center_border),
                                        inset(center_border),
                                        r(min_radius, sym_size // 2 - 1),
                                        shape=im.shape)
     im[rr, cc] = vals
Exemple #6
0
    def spatial_draw(self,
                     image_size,
                     pose_joints,
                     joint_line_list,
                     radius=2,
                     line_color=[118, 214, 255],
                     cycle_color=[66, 115, 177]):
        colors = np.ones(shape=image_size + (3, ), dtype=np.uint8) * 255.0
        mask = np.zeros(shape=image_size, dtype=np.uint8)
        for f, t in joint_line_list:
            yy, xx, val = line_aa(pose_joints[0, f], pose_joints[1, f],
                                  pose_joints[0, t], pose_joints[1, t])
            yy[yy > image_size[0] - 1] = image_size[0] - 1
            xx[xx > image_size[1] - 1] = image_size[1] - 1
            mask[yy, xx] = 1
        mask = morphology.dilation(mask, morphology.disk(radius=1))
        colors[mask == 1] = line_color

        mask = np.zeros(shape=image_size, dtype=np.uint8)
        for i in range(pose_joints.shape[1]):
            yy, xx, val = circle_perimeter_aa(pose_joints[0, i],
                                              pose_joints[1, i],
                                              radius=radius)
            # yy, xx = disk((pose_joints[0,i], pose_joints[1,i]), radius=radius, shape=im_size)
            yy[yy > image_size[0] - 1] = image_size[0] - 1
            xx[xx > image_size[1] - 1] = image_size[1] - 1
            mask[yy, xx] = 1
        # mask = morphology.dilation(mask, morphology.disk(radius=1))
        colors[mask == 1] = cycle_color

        return colors
Exemple #7
0
    def circle(self,
               row: int,
               col: int,
               radius: float,
               color: ColorType,
               fill: bool = False,
               alpha=1.0) -> 'Layer':
        """
        Draw a circle centered on the specified row and column,
        with the given radius.

        :param row: Center row of circle
        :param col: Center column of circle
        :param radius: Radius of circle
        :param color: Color to draw with
        :param fill: True if the circle should be filled

        :return: This frame instance
        """
        if fill:
            rr, cc = draw.circle(row,
                                 col,
                                 round(radius),
                                 shape=self.matrix.shape)
            self._draw(rr, cc, color, alpha)

        else:
            rr, cc, aa = draw.circle_perimeter_aa(row,
                                                  col,
                                                  round(radius),
                                                  shape=self.matrix.shape)
            self._draw(rr, cc, color, aa)

        return self
def run(in_fname, out_fname):
    """
    draw lattice lines between all points. Lines are brighter based on the frequency 
    of the occurance of lines with the same angle
    """
    img = image_utils.read_image(in_fname)
    data = image_utils.image_to_matrix(img)
    edge_data = image_utils.image_to_matrix(img)
    point_data = image_utils.image_to_matrix(img)

    points = local_maxima.run(data)

    #for point in points:
    #    print(point)

    llist = all_point_pairs_as_lines(points)
    llist = filter_segments_with_colinear_points(llist, points)

    # Draw blue edges between neighboring points
    for line in llist:
        rr, cc, lum = line_aa(line[0][0], line[0][1], line[1][0], line[1][1])
        edge_data[rr, cc] = np.maximum(edge_data[rr, cc], lum * 255)

    #  Draw red circles around all points
    for point in points:
        rr, cc, lum = circle_perimeter_aa(point[0], point[1], 4)
        point_data[rr, cc] = np.maximum(point_data[rr, cc], lum * 255)

    out_data = np.dstack((point_data, data, edge_data))

    out_img = image_utils.matrix_to_image(out_data)
    image_utils.write_image(out_img, out_fname)
Exemple #9
0
def observe():
    '''
    Plot the groundtruth bounding circle and the predicted bounding circle.
    The groundtruth is in green and the prediction in red.
    '''
    for _ in range(10):
        netx = Net()
        nety = Net()
        netr = Net()
        device = torch.device('cuda')
        netx.load_state_dict(torch.load('q2x.pt'))
        nety.load_state_dict(torch.load('q2y.pt'))
        netr.load_state_dict(torch.load('q2r.pt'))
        netx.to(device)
        nety.to(device)
        netr.to(device)

        params, img = noisy_circle(200, 50, 2)
        img_tensor = img.reshape(200, 200, 1).transpose((2, 0, 1))
        tensor = torch.from_numpy(img_tensor)
        tensor = tensor.unsqueeze(1).float()
        if use_gpu:
            tensor = tensor.cuda()
        resx = netx(tensor).detach().cpu().numpy()[0]
        resy = nety(tensor).detach().cpu().numpy()[0]
        resr = netr(tensor).detach().cpu().numpy()[0]
        img = cv2.cvtColor((img * 255).astype(np.uint8), cv2.COLOR_GRAY2RGB)

        rr, cc, val = circle_perimeter_aa(int(resx), int(resy), int(resr))
        valid = ((rr >= 0) & (rr < img.shape[0]) & (cc >= 0) &
                 (cc < img.shape[1]))

        img[rr[valid], cc[valid], 0] = 255
        img[rr[valid], cc[valid], 1] = 0
        img[rr[valid], cc[valid], 2] = 0

        rr, cc, val = circle_perimeter_aa(params[0], params[1], params[2])
        valid = ((rr >= 0) & (rr < img.shape[0]) & (cc >= 0) &
                 (cc < img.shape[1]))

        img[rr[valid], cc[valid], 0] = 0
        img[rr[valid], cc[valid], 1] = 255
        img[rr[valid], cc[valid], 2] = 0

        print(iou((int(resx), int(resy), int(resr)), params))
        plt.imshow(img)
        plt.show()
Exemple #10
0
	def getAnnotation(self, image, targets, d, values=[0.1,0.25,0.5]):
		annotations = np.zeros_like(image)
		for target in targets:
			for value in values:
				rr, cc, intensity = circle_perimeter_aa( int(target[0][1]), int(target[0][0]), int(value*d), shape = annotations.shape)
				annotations[rr,cc] = intensity*255

		return annotations
Exemple #11
0
def draw_disk_aa(img, row, col, rad=7, color=black):
    expanded_color = np.expand_dims(np.expand_dims(np.array(color), 0), 0)
    rr, cc, val = circle_perimeter_aa(row, col, rad)
    img[rr, cc, :] = np.expand_dims(val, 2)
    img[rr, cc, :] = img[rr, cc, :] * (1.0 - expanded_color)
    img[rr, cc, :] = 0.95 - img[rr, cc, :]
    rr, cc = circle(row, col, rad)
    img[rr, cc, :] = expanded_color
Exemple #12
0
def draw_circle_aa(img, row, col, rad, color=(0.0, 0.0, 0.0)):
    expanded_color = np.expand_dims(np.expand_dims(np.array(color), 0), 0)
    rr, cc, val = circle_perimeter_aa(row, col, rad)
    img[rr, cc, :] = np.expand_dims(val, 2)
    img[rr, cc, :] = img[rr, cc, :] * (1.0 - expanded_color)
    img[rr, cc, :] = 1.0 - img[rr, cc, :]
    rr, cc = circle(row, col, rad)
    img[rr, cc, :] = expanded_color
def draw_circle(img, row, col, rad):
    rr, cc, val = circle_perimeter_aa(row, col, rad)
    valid = (
        (rr >= 0) &
        (rr < img.shape[0]) &
        (cc >= 0) &
        (cc < img.shape[1])
    )
    img[rr[valid], cc[valid]] = val[valid]
Exemple #14
0
def stroke_to_circle_coordinates(center1, center2, radius):
    circle_geometries = []
    circle_antialiased = []
    for center in (center1, center2):
        rr, cc = skd.circle(center[0], center[1], radius)
        val = np.ones(len(rr))
        circle_geometries.append((rr, cc, val))
        aarr, aacc, aaval = skd.circle_perimeter_aa(center[0], center[1], radius)
        circle_antialiased.append((aarr, aacc, aaval))
    return {'solid':circle_geometries, 'antialiased':circle_antialiased}
def test_linear_warp_polar():
    radii = [5, 10, 15, 20]
    image = np.zeros([51, 51])
    for rad in radii:
        rr, cc, val = circle_perimeter_aa(25, 25, rad)
        image[rr, cc] = val
    warped = warp_polar(image, radius=25)
    profile = warped.mean(axis=0)
    peaks = peak_local_max(profile)
    assert np.alltrue([peak in radii for peak in peaks])
Exemple #16
0
 def double_circle(im):
     """two circles, less clipped that the single circle"""
     c_x, c_y, radius = inner_circle(im)
     radians = 2 * np.pi * np.random.uniform()
     x = c_x + radius * math.cos(radians)
     y = c_y + radius * math.sin(radians)
     r2 = r(3, radius)
     rr, cc, vals = circle_perimeter_aa(int(round(y)),
                                        int(round(x)),
                                        r2,
                                        shape=im.shape)
     im[rr, cc] += vals
def create_one_imprint(xy_speed=50, bead_size=0, center=0.5, z_speed=1.0):
    focus_z = np.linspace(z_speed * (-2 + 2 * center),
                          z_speed * (2 - 2 * (1 - center)), args.stack_size)
    stack_z = np.linspace(-1.0, 1.0, args.stack_size)
    pad = args.imprint_size - args.psf_size
    angle_generation = np.deg2rad(0)

    params = Params()
    params.magnification = 20
    params.n = 1.33
    params.na = 0.45
    params.wavelength = 500
    params.pixelsize = 45
    params.tubelength = 200
    params.sph = 0.0
    params.size = args.psf_size
    params.ast = 0

    psf_3d = []
    ii = 0
    for i in stack_z:
        params.focus = focus_z[ii]
        psf, wavefront, pupil_diameter = get_psf(params)
        #plt.imshow(psf)
        #plt.show()
        psf = np.pad(psf, pad, mode='constant')
        psf = shift(psf, (np.cos(angle_generation) * 50 * xy_speed * i,
                          np.sin(angle_generation) * 50 * xy_speed * i),
                    order=3)
        psf_3d.append(psf)
        ii += 1

    psf_3d = np.asarray(psf_3d)
    psf_3d_projection = np.sum(psf_3d, axis=0)
    img = np.zeros((args.imprint_size, args.imprint_size))
    center = (args.imprint_size // 2 + 1, args.imprint_size // 2 + 1)
    img[center] = 1.0
    bead_size = int(np.floor(bead_size * 5))
    if bead_size > 0:
        rr, cc, val = circle_perimeter_aa(center[0], center[1], bead_size)
        img[rr, cc] = val * 1.0
        rr, cc = circle(center[0], center[1], bead_size)
        img[rr, cc] = 1.0
    img = normalize(img)

    img = convolve(img, psf_3d_projection, padding='reflect') * args.stack_size

    img = resize(img, (args.imprint_size + 1, args.imprint_size + 1))
    #write_tiff_stack('psf3d.tiff', psf_3d)
    #io.imsave('psf3d_projection.tiff', psf_3d_projection)
    #plt.imshow(img)
    #plt.show()
    return img
def test_log_warp_polar():
    radii = [np.exp(2), np.exp(3), np.exp(4), np.exp(5),
             np.exp(5)-1, np.exp(5)+1]
    radii = [int(x) for x in radii]
    image = np.zeros([301, 301])
    for rad in radii:
        rr, cc, val = circle_perimeter_aa(150, 150, rad)
        image[rr, cc] = val
    warped = warp_polar(image, radius=200, scaling='log')
    profile = warped.mean(axis=0)
    peaks_coord = peak_local_max(profile)
    peaks_coord.sort(axis=0)
    gaps = peaks_coord[1:] - peaks_coord[:-1]
    assert np.alltrue([x >= 38 and x <= 40 for x in gaps])
    def draw_circle(self, data, cX, cY, r, clr, alpha=1.0):
        '''
		Draw a circle with the given color and opacity.

		data -- image to draw to
		cX -- x value of circle center
		cY -- y value of circle center
		r -- radius of circle
		clr -- line color, triple of values
		alpha -- opacity (default 1.0)
		'''

        cY = int(cY * self.imgH)
        cX = int(cX * self.imgW)
        r = int(r * self.imgW)
        rr, cc, val = circle_perimeter_aa(cY, cX, r)
        set_color(data, (rr, cc), clr, val)
Exemple #20
0
    def _draw_triangles(self, tgt):
        mod = self._mod_hough
        for (p0, p1, p2), (y, x) in mod.barycenter.items():
            pois = (p0, p1), (p0, p2), (p1, p2)
            py, px = zip(*[mod.pois[a][b] for a, b in pois])

            rr, cc = skd.polygon_perimeter(py + (py[0], ),
                                           px + (px[0], ),
                                           shape=tgt.shape)

            tgt[rr, cc] = [255, 255, 255]

            r = (np.max(py) - np.min(py)) * 2
            rr, cc, val = skd.circle_perimeter_aa(y, x, r, shape=tgt.shape)

            tgt[rr, cc, 0] += val * 255
            tgt[tgt > 255] = 255
Exemple #21
0
    def inner_circle(im):
        """returns centerX, centerY, radius"""
        c_x = inset(5)
        c_y = inset(5)
        max_r = min(c_x, c_y)
        max_r = min(max_r, sym_size - 1 - c_x)
        max_r = min(max_r, sym_size - 1 - c_y)
        radius = max_r
        while radius > 4:
            if r(0, 1) == 1:
                radius -= 1
            else:
                break

        rr, cc, vals = circle_perimeter_aa(c_y, c_x, radius, shape=im.shape)
        im[rr, cc] += vals
        return c_x, c_y, radius
Exemple #22
0
	def plotTrajectory(self):
		trajectory = np.zeros( ( self.nFrames, self.frameSize[0], self.frameSize[1] ), dtype = np.uint8 )
		self.getTargets(self.data["I"][0,:,:,0], 'point', n = 1, r = 1)

		if self.targets:
			for t in range(self.nFrames-1):
				transform = self.compileTransform(t, inverse = True)

				for i, points in enumerate(self.targets):
					self.targets[i] = [  np.array( transform.TransformPoint( point ) ) for point in points ]

					rr,cc,val = circle_perimeter_aa( int(points[0][1]), int(points[0][0]), 2)
					trajectory[t,rr,cc] = 255*val

					rr,cc = circle( int(points[0][1]), int(points[0][0]), 2 )
					trajectory[t,rr,cc] = 255
					

		self.saveImage( sitk.GetImageFromArray(trajectory), self.nextFileName("trajectory") )
def draw_circle(image, coordinate, color=None, radius=10):
    """ Draw a circle at the [y_height, x_width] coordinate of an image.

        Requires scikit-image, http://scikit-image.org
        If it is not available this function is a no-op.
    """
    if circle_perimeter_aa is not None and set_color is not None:
        image_shape_len = len(image.shape)
        if image_shape_len == 4:
            batch, y_height, x_width, channels = image.shape
        elif image_shape_len == 3 and image.shape[0] == 1:
            batch, y_height, x_width = image.shape
            channels = 1
        elif image_shape_len == 3 and image.shape[2] == 1:
            y_height, x_width, channels = image.shape
            batch = 1
        elif image_shape_len == 2:
            y_height, x_width = image.shape
            batch = 1
            channels = 1

        if color is None:
            if channels == 1:
                color = [255]
            else:
                color = [0, 255, 255]
        image = np.squeeze(image)
        y, x = np.array(coordinate, dtype=np.int32)
        # please note that skimage uses a funky coordinate system:
        # origin in the top left with coordinates ordered
        # (y, x) where
        # +y is down from the top left corner and
        # +x is right from the top left corner
        rr, cc, aa = circle_perimeter_aa(y, x, radius, shape=image.shape)
        set_color(image, (rr, cc), color, alpha=aa)
        # axs.imshow(np.squeeze(frame))
        if image_shape_len > len(image.shape):
            # return the image to the shape that was provided
            image = np.expand_dims(image, axis=0)

    return image
Exemple #24
0
	def getDisplacementMap(self, xx, yy, steps, scale, mask):
		xx = sitk.GetArrayFromImage(xx)
		yy = sitk.GetArrayFromImage(yy)

		dx = int(self.frameSize[0] / steps)
		dy = int(self.frameSize[1] / steps)

		dmap = np.ones( (self.frameSize[0], self.frameSize[1]), dtype = 'uint8' ) * 255

		for x in range(0, self.frameSize[0], dx):
			for y in range(0, self.frameSize[1], dy):

				if mask[y,x] > 0:
					rr,cc,val = circle_perimeter_aa( y, x, 2 )
					print(rr,cc)
					dmap[rr,cc] = 255 - (val * 58)
					
					rr,cc,val = line_aa( y, x, int(y + yy[y,x] * scale), int(x + xx[y,x] * scale) )
					print(rr,cc)
					dmap[rr,cc] = 255- (val * 255)
		return dmap
Exemple #25
0
	def reconstructSignal(self, outline = True):
		print("\n########## Reconstructing Signal ##########\n")

		reconstructed = np.zeros( (self.nFrames, 2, self.frameSize[0], self.frameSize[1]), dtype = "uint8" )

		for t, nuclearSlice in enumerate(self.data['N']):
			reconstructedSlice = np.zeros( (2, self.frameSize[0], self.frameSize[1]) )
			for centroid, radius, signal in zip(nuclearSlice['centroid'], nuclearSlice['radius'], nuclearSlice['signal']):
				
				nuclearRow = int(centroid[1])
				nuclearColumn = int(centroid[0])

				rr, cc = circle( nuclearRow, nuclearColumn, radius )
				reconstructedSlice[0, rr,cc ] = int(signal)
				
				if outline:
					rr, cc, intensity = circle_perimeter_aa( nuclearRow, nuclearColumn, int(radius)+4 )
					reconstructedSlice[1,rr,cc] = 100*intensity

			reconstructed[t] = reconstructedSlice

		imsave( os.path.join( self.outputDir, "reconstructedSignal.tif"), reconstructed, imagej = True ) 
Exemple #26
0
    def _drawCircle(self, array, xind, yind, xcen, ycen, radius, value=1):
        """ Draw a circle in an array, of a given radius centered at (ycen,xcen)
        where the coordinates of the array indixes are (yind, xind)
        """

        if self._antialias:
            # use anti-aliased circle
            #  see http://scikit-image.org/docs/dev/auto_examples/plot_shapes.html#example-plot-shapes-py
            from skimage.draw import circle_perimeter_aa
            # assuming xind and yind are monotonic linear series,
            # convert to pixel coords
            pxscl = xind[0,1]-xind[0,0]
            xpix = int(round((xcen-xind[0,0])/pxscl))
            ypix = int(round((ycen-yind[0,0])/pxscl))
            rad =  int(round(radius/pxscl))
            rr,cc,val = circle_perimeter_aa(ypix,xpix,rad)
            array[rr,cc] = val
            # FIXME the above is imperfect because the method in skimage only works
            # on integer coordinates. TBD to see if we care enough to do anything better than
            # that.

        r = np.sqrt((xind-xcen) ** 2 + (yind-ycen) ** 2)
        array[r<radius]=value
Exemple #27
0
    def _drawCircle(self, array, xind, yind, xcen, ycen, radius, value=1):
        """ Draw a circle in an array, of a given radius centered at (ycen,xcen)
        where the coordinates of the array indixes are (yind, xind)
        """

        if self._antialias:
            # use anti-aliased circle
            #  see http://scikit-image.org/docs/dev/auto_examples/plot_shapes.html#example-plot-shapes-py
            from skimage.draw import circle_perimeter_aa
            # assuming xind and yind are monotonic linear series,
            # convert to pixel coords
            pxscl = xind[0, 1] - xind[0, 0]
            xpix = int(round((xcen - xind[0, 0]) / pxscl))
            ypix = int(round((ycen - yind[0, 0]) / pxscl))
            rad = int(round(radius / pxscl))
            rr, cc, val = circle_perimeter_aa(ypix, xpix, rad)
            array[rr, cc] = val
            # FIXME the above is imperfect because the method in skimage only works
            # on integer coordinates. TBD to see if we care enough to do anything better than
            # that.

        r = np.sqrt((xind - xcen)**2 + (yind - ycen)**2)
        array[r < radius] = value
    def __transform(self):
        img_gray = io.imread(self.__img_path, True)
        
        thresh = filter.threshold_otsu(img_gray)
        data = img_gray < thresh
        s1, self.__distancia = morphology.medial_axis(data, return_distance=True)
        self.__s2 = s1

        for i in range(len(s1)):
            for j in range(len(s1)):
                if (s1[i,j] <> False): #Percorre o esqueleto da imagem
                    x, y,val = circle_perimeter_aa(i, j, int(self.__distancia[i,j]))

                    #desenha um circulo ao redor do pixel do esqueleto
                    #i,j coordenadas do centro  -- int(distance[i,j]=raio do circulo)
                    #x,y = índices dos pixels  ---- val = intensidade

                    #Define quais circulos devem ficar de acordo com o raio
                    if (int(self.__distancia[i,j]) > 0):
                        self.__s2[x, y] = True
                    else:
                        self.__s2[x, y] = False
                else:
                    self.__s2[i, j] = False        
    def draw_frame_plans(self, scr, state, plans, current_plan_idx,
                         current_plan_step_idx, idr_v, idr_adv,
                         plan_to_rewards_direct, plan_to_reward_indirect,
                         plan_to_reward, plans_ranking):
        mincolf = 0.2
        bgcolor = [0, 0, 0]
        image = np.zeros((720, 1280, 3), dtype=np.uint8)
        scr_main = ia.imresize_single_image(
            scr, (int(720 * 0.58), int(1280 * 0.58)))
        util.draw_image(image,
                        y=int((image.shape[0] - scr_main.shape[0]) / 2),
                        x=1280 - scr_main.shape[1] - 2,
                        other_img=scr_main,
                        copy=False)
        image = util.draw_text(
            image,
            x=1280 - (scr_main.shape[1] // 2) - 125,
            y=image.shape[0] - int(
                (image.shape[0] - scr_main.shape[0]) / 2) + 10,
            text="Framerate matches the one that the model sees (10fps).",
            size=10,
            color=[128, 128, 128])

        def draw_key(key):
            btn = [[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
                   [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                   [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                   [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]
            btn = np.array(btn, dtype=np.uint8) * 255
            btn = np.tile(btn[:, :, np.newaxis], (1, 1, 3))
            if key is None:
                return np.zeros_like(btn)
            elif key == "":
                return btn
            else:
                return util.draw_text(btn,
                                      x=3,
                                      y=3,
                                      text=key,
                                      size=9,
                                      color=[255, 255, 255])

        def multiaction_idx_to_image(multiaction_idx):
            #btn = np.pad(btn, ((0, 0), (0, 4), (0, 0)), mode="constant", constant_values=0)
            key_to_img = dict()
            for key in ["W", "A", "S", "D", None]:
                key_to_img[key] = draw_key(key)

            multiaction = actionslib.ALL_MULTIACTIONS[multiaction_idx]
            sw = 1.0 if multiaction[0] == "W" else mincolf
            sa = 1.0 if multiaction[1] == "A" else mincolf
            ss = 1.0 if multiaction[0] == "S" else mincolf
            sd = 1.0 if multiaction[1] == "D" else mincolf
            buttons = [[
                key_to_img[None], key_to_img["W"] * sw, key_to_img[None]
            ],
                       [
                           key_to_img["A"] * sa, key_to_img["S"] * ss,
                           key_to_img["D"] * sd
                       ]]
            buttons_img = np.vstack([
                np.hstack([btn.astype(np.uint8) for btn in buttons[0]]),
                np.hstack([btn.astype(np.uint8) for btn in buttons[1]])
            ])
            buttons_img = np.pad(buttons_img, ((0, 0), (0, 4), (0, 0)),
                                 mode="constant",
                                 constant_values=0)
            return buttons_img

        multiaction_idx_to_image_dict = dict([
            (i, multiaction_idx_to_image(i))
            for i in range(len(actionslib.ALL_MULTIACTIONS))
        ])
        multiaction_to_image_dict = dict([
            (ma, multiaction_idx_to_image(i))
            for i, ma in enumerate(actionslib.ALL_MULTIACTIONS)
        ])

        def plan_to_image(p_multiactions,
                          p_direct_rewards,
                          p_v,
                          padding_bottom=8,
                          minwidth=200):
            plan_viz = [multiaction_to_image_dict[ma] for ma in p_multiactions]
            #plan_viz = [np.pad(a, ((0, 20), (2, 2), (0, 0)), mode="constant", constant_values=0) for a in plan_viz]
            plan_viz = [
                np.pad(a, ((0, 20), (0, 1), (0, 0)),
                       mode="constant",
                       constant_values=0) for a in plan_viz
            ]
            if p_direct_rewards is not None:
                for j in xrange(len(plan_viz)):
                    #plan_viz[j] = util.draw_text(plan_viz[j], x=9, y=plan_viz[j].shape[0]-16, text="r", size=9, color=[128, 128, 128])
                    plan_viz[j] = util.draw_text(plan_viz[j],
                                                 x=11,
                                                 y=plan_viz[j].shape[0] - 13,
                                                 text="r %.1f" %
                                                 (p_direct_rewards[j], ),
                                                 size=9,
                                                 color=[128, 128, 128])

            if p_v is not None:
                plan_viz.append(np.zeros_like(plan_viz[-1]))
                #plan_viz[-1] = util.draw_text(plan_viz[-1], x=3, y=5, text="V", size=9, color=[128, 128, 128])
                #plan_viz[-1] = util.draw_text(plan_viz[-1], x=9, y=11, text="V %.1f" % (p_v,), size=9, color=[255, 255, 255])
                plan_viz[-1] = util.draw_text(plan_viz[-1],
                                              x=5,
                                              y=16,
                                              text="V %.1f" % (p_v, ),
                                              size=9,
                                              color=[255, 255, 255])

            plan_viz = np.hstack(plan_viz)
            width_extend = minwidth - plan_viz.shape[1] if plan_viz.shape[
                1] < minwidth else 0
            #print("width_extend", width_extend, minwidth, plan_viz.shape[0])
            plan_viz = np.pad(plan_viz,
                              ((0, padding_bottom), (0, width_extend), (0, 0)),
                              mode="constant",
                              constant_values=0)

            return plan_viz

        # -------------
        # current plan
        # -------------
        current_plan_viz = plan_to_image(
            plans[current_plan_idx][current_plan_step_idx:], None, None)
        #current_plan_viz = np.pad(current_plan_viz, ((50, 0), (20, 0), (0, 0)), mode="constant", constant_values=0)
        current_plan_viz = np.pad(current_plan_viz, ((50, 0), (2, 0), (0, 0)),
                                  mode="constant",
                                  constant_values=0)
        current_plan_viz = util.draw_text(current_plan_viz,
                                          x=4,
                                          y=4,
                                          text="Current Plan",
                                          color=[255, 255, 255])
        util.draw_image(image,
                        y=10,
                        x=10,
                        other_img=current_plan_viz,
                        copy=False)

        # -------------
        # best plans
        # -------------
        best_plans_viz = []
        for i in range(4):
            plan_idx = plans_ranking[::-1][i]
            plan = plans[plan_idx]
            r = plan_to_rewards_direct[plan_idx]
            v = plan_to_reward_indirect[plan_idx]
            plan_viz = plan_to_image(plan, r, v)
            best_plans_viz.append(plan_viz)

        best_plans_viz = np.vstack(best_plans_viz)

        #best_plans_viz = np.pad(best_plans_viz, ((50, 30), (20, 0), (0, 0)), mode="constant", constant_values=0)
        best_plans_viz = np.pad(best_plans_viz, ((50, 30), (2, 0), (0, 0)),
                                mode="constant",
                                constant_values=0)
        best_plans_viz = util.draw_text(best_plans_viz,
                                        x=4,
                                        y=4,
                                        text="Best Plans",
                                        color=[255, 255, 255])
        best_plans_viz = util.draw_text(
            best_plans_viz,
            x=30,
            y=best_plans_viz.shape[0] - 20,
            text=
            "r = expected direct reward at timestep (discounted)\nV = expected indirect reward at last timestep (discounted)",
            color=[128, 128, 128],
            size=9)

        util.draw_image(image,
                        y=110,
                        x=10,
                        other_img=best_plans_viz,
                        copy=False)

        # --------------
        # top15
        # --------------
        n = 15
        top_viz = []
        counts_ud = dict([(action, 0)
                          for action in actionslib.ACTIONS_UP_DOWN])
        counts_lr = dict([(action, 0)
                          for action in actionslib.ACTIONS_LEFT_RIGHT])
        for i in range(n):
            plan_idx = plans_ranking[::-1][i]
            plan = plans[plan_idx]
            for ma in plan:
                counts_ud[ma[0]] += 1
                counts_lr[ma[1]] += 1
        sum_ud = np.sum(list(counts_ud.values()))
        sum_lr = np.sum(list(counts_lr.values()))
        fracs_ud = [
            counts_ud["W"] / sum_ud, counts_ud["S"] / sum_ud,
            counts_ud["~WS"] / sum_ud
        ]
        fracs_lr = [
            counts_lr["A"] / sum_lr, counts_lr["D"] / sum_lr,
            counts_lr["~AD"] / sum_lr
        ]

        def draw_bar(frac, key, h=30, w=20, margin_right=15):
            bar = np.zeros((h, 1), dtype=np.uint8) + 32
            bar[0:int(h * frac) + 1] = 255
            bar = np.flipud(bar)
            bar = np.tile(bar[:, :, np.newaxis], (1, w, 3))
            bar = np.pad(bar, ((20, 30), (0, margin_right), (0, 0)),
                         mode="constant",
                         constant_values=0)
            textx = 5
            if frac * 100 >= 10:
                textx = textx - 3
            elif frac * 100 >= 100:
                textx = textx - 6
            bar = ia.draw_text(bar,
                               x=textx,
                               y=2,
                               text="%.0f%%" % (frac * 100, ),
                               size=8,
                               color=[255, 255, 255])
            keyimg = draw_key(key)
            util.draw_image(bar,
                            x=(w // 2) - keyimg.shape[1] // 2,
                            y=bar.shape[0] - keyimg.shape[0] - 8,
                            other_img=keyimg,
                            copy=False)
            return bar

        bars_ud = [
            draw_bar(fracs_ud[0], "W"),
            draw_bar(fracs_ud[1], "S"),
            draw_bar(fracs_ud[2], "", margin_right=55)
        ]
        bars_lr = [
            draw_bar(fracs_lr[0], "A"),
            draw_bar(fracs_lr[1], "D"),
            draw_bar(fracs_lr[2], "")
        ]
        top_viz = np.hstack(bars_ud + bars_lr)
        top_viz = np.pad(top_viz, ((50, 30), (20, 180), (0, 0)),
                         mode="constant",
                         constant_values=0)
        top_viz = util.draw_text(top_viz,
                                 x=4,
                                 y=4,
                                 text="Share Of Keys (Top %d Plans)" % (n, ),
                                 color=[255, 255, 255])
        top_viz = util.draw_text(
            top_viz,
            x=4,
            y=top_viz.shape[0] - 20,
            text=
            "Percent of actions among top %d plans that contain a top/down or left/right key"
            % (n, ),
            color=[128, 128, 128],
            size=9)

        util.draw_image(image, y=430, x=10, other_img=top_viz, copy=False)

        # --------------
        # other
        # --------------
        other_viz = np.zeros((300, 500, 3), dtype=np.uint8)
        other_viz = util.draw_text(other_viz,
                                   x=4,
                                   y=4,
                                   text="Speed",
                                   color=[255, 255, 255])
        other_viz = util.draw_text(other_viz,
                                   x=150,
                                   y=4,
                                   text="Steering Wheel",
                                   color=[255, 255, 255])

        other_viz = util.draw_text(
            other_viz,
            x=12,
            y=65,
            text="%d km/h" % (state.speed if state.speed is not None else -1),
            color=[255, 255, 255])

        sw_angle = state.steering_wheel_cnn if state.steering_wheel_cnn is not None else 0
        sw_circle = np.zeros((80, 80, 3), dtype=np.int32)
        if sw_angle <= -360 or sw_angle >= 360:
            rr, cc = draw.circle(r=40, c=40, radius=30)
            sw_circle[rr, cc, :] = 128
        col = [128, 128, 128] if -360 < sw_angle < 360 else [255, 255, 255]
        if abs(sw_angle % 360) > 1:
            if sw_angle < 0:
                sw_circle = util.draw_direction_circle(
                    sw_circle,
                    y=40,
                    x=40,
                    r_inner=0,
                    r_outer=30,
                    angle_start=360 - (abs(int(sw_angle)) % 360),
                    angle_end=360,
                    color_border=col,
                    color_fill=col
                    #color_fill=[255,0,0]
                )
                #sw_circle = util.draw_text(sw_circle, x=5, y=5, text="%.2f\n%.2f" % (abs(int(sw_angle)) % 360, 360-(abs(int(sw_angle)) % 360)), size=12, color=[255, 255, 255])
            else:
                sw_circle = util.draw_direction_circle(
                    sw_circle,
                    y=40,
                    x=40,
                    r_inner=0,
                    r_outer=30,
                    angle_start=0,
                    angle_end=int(sw_angle) % 360,
                    color_border=col,
                    color_fill=col
                    #color_fill=[0,255,0]
                )
        rr, cc, val = draw.circle_perimeter_aa(40, 40, radius=30)
        #sw_circle[rr, cc, :] = sw_circle[rr, cc, :] + np.tile((val * 255)[:,:,np.newaxis], (1, 1, 3))
        sw_circle[rr, cc, :] += np.tile(
            (val * 255).astype(np.int32)[:, np.newaxis], (1, 3))
        sw_circle = np.clip(sw_circle, 0, 255).astype(np.uint8)
        sw_circle = np.pad(sw_circle, ((0, 0), (0, 140), (0, 0)),
                           mode="constant",
                           constant_values=0)
        sw_circle = util.draw_text(sw_circle,
                                   x=92,
                                   y=27,
                                   text="%d deg" % (sw_angle, ),
                                   color=[255, 255, 255])
        util.draw_image(other_viz,
                        x=150,
                        y=40,
                        other_img=sw_circle,
                        copy=False)

        util.draw_image(image, y=590, x=10, other_img=other_viz, copy=False)

        return image
Exemple #30
0
img[rr, cc, :] = (1, 0, 1)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=-math.pi / 4.)
img[rr, cc, :] = (0, 0, 1)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 2.)
img[rr, cc, :] = (1, 1, 1)

ax1.imshow(img)
ax1.set_title('No anti-aliasing')
ax1.axis('off')


from skimage.draw import line_aa, circle_perimeter_aa


img = np.zeros((100, 100), dtype=np.double)

# anti-aliased line
rr, cc, val = line_aa(12, 12, 20, 50)
img[rr, cc] = val

# anti-aliased circle
rr, cc, val = circle_perimeter_aa(60, 40, 30)
img[rr, cc] = val


ax2.imshow(img, cmap=plt.cm.gray, interpolation='nearest')
ax2.set_title('Anti-aliasing')
ax2.axis('off')

plt.show()
Exemple #31
0
def daisy(image,
          step=4,
          radius=15,
          rings=3,
          histograms=8,
          orientations=8,
          normalization='l1',
          sigmas=None,
          ring_radii=None,
          visualize=False):
    """Extract DAISY feature descriptors densely for the given image.

    DAISY is a feature descriptor similar to SIFT formulated in a way that
    allows for fast dense extraction. Typically, this is practical for
    bag-of-features image representations.

    The implementation follows Tola et al. [1]_ but deviate on the following
    points:

      * Histogram bin contribution are smoothed with a circular Gaussian
        window over the tonal range (the angular range).
      * The sigma values of the spatial Gaussian smoothing in this code do not
        match the sigma values in the original code by Tola et al. [2]_. In
        their code, spatial smoothing is applied to both the input image and
        the center histogram. However, this smoothing is not documented in [1]_
        and, therefore, it is omitted.

    Parameters
    ----------
    image : (M, N) array
        Input image (grayscale).
    step : int, optional
        Distance between descriptor sampling points.
    radius : int, optional
        Radius (in pixels) of the outermost ring.
    rings : int, optional
        Number of rings.
    histograms  : int, optional
        Number of histograms sampled per ring.
    orientations : int, optional
        Number of orientations (bins) per histogram.
    normalization : [ 'l1' | 'l2' | 'daisy' | 'off' ], optional
        How to normalize the descriptors

          * 'l1': L1-normalization of each descriptor.
          * 'l2': L2-normalization of each descriptor.
          * 'daisy': L2-normalization of individual histograms.
          * 'off': Disable normalization.

    sigmas : 1D array of float, optional
        Standard deviation of spatial Gaussian smoothing for the center
        histogram and for each ring of histograms. The array of sigmas should
        be sorted from the center and out. I.e. the first sigma value defines
        the spatial smoothing of the center histogram and the last sigma value
        defines the spatial smoothing of the outermost ring. Specifying sigmas
        overrides the following parameter.

            ``rings = len(sigmas) - 1``

    ring_radii : 1D array of int, optional
        Radius (in pixels) for each ring. Specifying ring_radii overrides the
        following two parameters.

            ``rings = len(ring_radii)``
            ``radius = ring_radii[-1]``

        If both sigmas and ring_radii are given, they must satisfy the
        following predicate since no radius is needed for the center
        histogram.

            ``len(ring_radii) == len(sigmas) + 1``

    visualize : bool, optional
        Generate a visualization of the DAISY descriptors

    Returns
    -------
    descs : array
        Grid of DAISY descriptors for the given image as an array
        dimensionality  (P, Q, R) where

            ``P = ceil((M - radius*2) / step)``
            ``Q = ceil((N - radius*2) / step)``
            ``R = (rings * histograms + 1) * orientations``

    descs_img : (M, N, 3) array (only if visualize==True)
        Visualization of the DAISY descriptors.

    References
    ----------
    .. [1] Tola et al. "Daisy: An efficient dense descriptor applied to wide-
           baseline stereo." Pattern Analysis and Machine Intelligence, IEEE
           Transactions on 32.5 (2010): 815-830.
    .. [2] http://cvlab.epfl.ch/software/daisy
    """

    check_nD(image, 2, "img")

    image = img_as_float(image)

    # Validate parameters.
    if sigmas is not None and ring_radii is not None \
            and len(sigmas) - 1 != len(ring_radii):
        raise ValueError('`len(sigmas)-1 != len(ring_radii)`')
    if ring_radii is not None:
        rings = len(ring_radii)
        radius = ring_radii[-1]
    if sigmas is not None:
        rings = len(sigmas) - 1
    if sigmas is None:
        sigmas = [radius * (i + 1) / float(2 * rings) for i in range(rings)]
    if ring_radii is None:
        ring_radii = [radius * (i + 1) / float(rings) for i in range(rings)]
    if normalization not in ['l1', 'l2', 'daisy', 'off']:
        raise ValueError('Invalid normalization method.')

    # Compute image derivatives.
    dx = cp.zeros(image.shape)
    dy = cp.zeros(image.shape)
    dx[:, :-1] = cp.diff(image, n=1, axis=1)
    dy[:-1, :] = cp.diff(image, n=1, axis=0)

    # Compute gradient orientation and magnitude and their contribution
    # to the histograms
    grad_mag = dx * dx
    grad_mag += dy * dy
    cp.sqrt(grad_mag, out=grad_mag)
    grad_ori = cp.arctan2(dy, dx)
    pi = cp.pi
    orientation_kappa = orientations / pi
    orientation_angles = [
        2 * o * pi / orientations - pi for o in range(orientations)
    ]
    hist = cp.empty((orientations, ) + image.shape, dtype=float)
    for i, o in enumerate(orientation_angles):
        # Weigh bin contribution by the circular normal distribution
        hist[i, :, :] = cp.exp(orientation_kappa * cp.cos(grad_ori - o))
        # Weigh bin contribution by the gradient magnitude
        hist[i, :, :] = cp.multiply(hist[i, :, :], grad_mag)

    # Smooth orientation histograms for the center and all rings.
    sigmas = [sigmas[0]] + sigmas
    hist_smooth = cp.empty((rings + 1, ) + hist.shape, dtype=float)
    for i in range(rings + 1):
        for j in range(orientations):
            hist_smooth[i, j, :, :] = gaussian_filter(hist[j, :, :],
                                                      sigma=sigmas[i])

    # Assemble descriptor grid.
    theta = [2 * pi * j / histograms for j in range(histograms)]
    desc_dims = (rings * histograms + 1) * orientations
    descs = cp.empty(
        (desc_dims, image.shape[0] - 2 * radius, image.shape[1] - 2 * radius))
    descs[:orientations, :, :] = hist_smooth[0, :, radius:-radius,
                                             radius:-radius]
    idx = orientations
    for i in range(rings):
        for j in range(histograms):
            y_min = radius + int(round(ring_radii[i] * math.sin(theta[j])))
            y_max = descs.shape[1] + y_min
            x_min = radius + int(round(ring_radii[i] * math.cos(theta[j])))
            x_max = descs.shape[2] + x_min
            descs[idx:idx + orientations, :, :] = hist_smooth[i + 1, :,
                                                              y_min:y_max,
                                                              x_min:x_max]
            idx += orientations
    descs = descs[:, ::step, ::step]
    descs = descs.swapaxes(0, 1).swapaxes(1, 2)

    # Normalize descriptors.
    if normalization != 'off':
        descs += 1e-10
        if normalization == 'l1':
            descs /= cp.sum(descs, axis=2)[:, :, cp.newaxis]
        elif normalization == 'l2':
            descs /= cp.sqrt(cp.sum(descs * descs, axis=2))[:, :, cp.newaxis]
        elif normalization == 'daisy':
            for i in range(0, desc_dims, orientations):
                norms = descs[:, :, i:i + orientations]
                norms = norms * norms
                norms = norms.sum(axis=2)
                cp.sqrt(norms, out=norms)
                descs[:, :, i:i + orientations] /= norms[:, :, cp.newaxis]

    if visualize:
        from skimage import draw
        from skimage.color import gray2rgb

        image = cp.asnumpy(image)
        descs_img = gray2rgb(image)
        for i in range(descs.shape[0]):
            for j in range(descs.shape[1]):
                # Draw center histogram sigma
                color = [1, 0, 0]
                desc_y = i * step + radius
                desc_x = j * step + radius
                rows, cols, val = draw.circle_perimeter_aa(
                    desc_y, desc_x, int(sigmas[0]))
                draw.set_color(descs_img, (rows, cols), color, alpha=val)
                max_bin = float(cp.max(descs[i, j, :]))
                for o_num, o in enumerate(orientation_angles):
                    # Draw center histogram bins
                    bin_size = descs[i, j, o_num] / max_bin
                    dy = sigmas[0] * bin_size * math.sin(o)
                    dx = sigmas[0] * bin_size * math.cos(o)
                    rows, cols, val = draw.line_aa(desc_y, desc_x,
                                                   int(desc_y + dy),
                                                   int(desc_x + dx))
                    draw.set_color(descs_img, (rows, cols), color, alpha=val)
                for r_num, r in enumerate(ring_radii):
                    color_offset = float(1 + r_num) / rings
                    color = (1 - color_offset, 1, color_offset)
                    for t_num, t in enumerate(theta):
                        # Draw ring histogram sigmas
                        hist_y = desc_y + int(round(r * math.sin(t)))
                        hist_x = desc_x + int(round(r * math.cos(t)))
                        rows, cols, val = draw.circle_perimeter_aa(
                            hist_y, hist_x, int(sigmas[r_num + 1]))
                        draw.set_color(descs_img, (rows, cols),
                                       color,
                                       alpha=val)
                        for o_num, o in enumerate(orientation_angles):
                            # Draw histogram bins
                            bin_size = descs[i, j, orientations + r_num *
                                             histograms * orientations +
                                             t_num * orientations + o_num]
                            bin_size /= max_bin
                            dy = sigmas[r_num + 1] * bin_size * math.sin(o)
                            dx = sigmas[r_num + 1] * bin_size * math.cos(o)
                            rows, cols, val = draw.line_aa(
                                hist_y, hist_x, int(hist_y + dy),
                                int(hist_x + dx))
                            draw.set_color(descs_img, (rows, cols),
                                           color,
                                           alpha=val)
        return descs, descs_img
    else:
        return descs
Exemple #32
0
logfile = [
    12, 13, 14, 15, 16, 17, 18, 23, 24, 25, 26, 27, 28, 34, 35, 36, 37, 38, 45,
    46, 47, 48, 56, 57, 58, 67, 68, 78
]
"""
2. 
"""
image_pixels = 10
# draw a circle outline for now.
img = np.zeros((image_pixels, image_pixels), dtype=np.float)
# then find all the 8 points where electrodes are.
x_center = image_pixels / 2
y_center = image_pixels / 2
radius = image_pixels / 2 - image_pixels / 10
# this is our series of coordinates to create lines from.
r, c, val = circle_perimeter_aa(x_center, y_center, radius)
#img[r, c] = val * 255

# electrode points:
theta_points = [
    np.pi, 5 * np.pi / 4, 3 * np.pi / 2, 7 * np.pi / 4, 0, np.pi / 4,
    np.pi / 2, 3 * np.pi / 4
]
n1 = np.add(x_center * np.ones(len(theta_points)),
            radius * np.cos(theta_points))  #  shift center
n2 = np.add(y_center * np.ones(len(theta_points)),
            radius * np.sin(theta_points))  #
x = []
y = []
for i in xrange(len(n1)):
    x.append(int(n1[i]))
            if area>400:
                coord2 = (properties[i].centroid[0]+4,properties[i].centroid[1]+4)
                eggs.append(coord2)
                if area>700:
                    coord3 = (properties[i].centroid[0]+10,properties[i].centroid[1]-10)
                    eggs.append(coord3)
                    if area>900:
                        coord4 = (properties[i].centroid[0]-10,properties[i].centroid[1]+10)
                        eggs.append(coord4)
            
    number = len(eggs)
    #print eggs
    print '%i eggs' %number
    
    radius = 22
    image.flags.writeable = True
    for i in range(len(eggs)):
        center_y, center_x = eggs[i]
        cx, cy,val = circle_perimeter_aa(int(center_x),int(center_y), radius)#,shape = image.shape)
        #image[cy,cx] = 255 
        try:        
            image[cy, cx] = 255# (220, 20, 20)# 0
        except IndexError:
            break
    
    ax = plt.axis()
    #plt.imshow(image, cmap=plt.cm.gray)
    plt.imshow(image,cmap = plt.gray())
    plt.show()
#plan: use area (or filled_area) to find the eggs, centroid? or coords to get the location of them
Exemple #34
0
def feature_finder(roi, image_set, feature, thresh=0.0):

    # Do some type checking on the arguments
    if type(roi) is not Polygon:
        raise TypeError("region_of_interest is not of type Polygon")
    if type(image_set) is not list:
        raise TypeError("image_set is not of type list")
    if type(feature) is not list:
        raise TypeError("feature is not of type list")
    if roi is None:
        raise TypeError("Invalid region_of_interest given in feature_finder.py")
    if image_set is None:
        raise TypeError("Invalid image given in feature_finder.py")
    if thresh > 1 or thresh < 0:
        raise TypeError("Invalid range given, must between 0 and 1")
    if not feature:
        raise TypeError("Features list is empty is Empty")
    if not image_set:
        raise TypeError("image_set is empty is Empty")

    # Create lists for the x and y points for easy calculation of min and max
    # and the masks/masked images
    # The results are stored in a keyed dictionary with the keys being the
    # respective features that were calculated.
    x_points, y_points = roi.exterior.coords.xy
    masks = []
    masked_images = []
    result = {}

    # Create a white polygon and make everything else black, creating a mask of
    # the region of interest
    for i in range(len(image_set)):
        # Create the masks
        masks.append(np.array(image_set[i]))

        # Create a polygon from the list of points given
        rr, cc = draw.polygon(y_points, x_points)

        # Take the created polygon and make a mask out of it
        masks[i][rr, cc] = 1
        masks[i][masks[i] != 1] = 0

        # Apply the mask to the original image
        masked_images.append(image_set[i] * masks[i])
        masked_images[i] = masked_images[i][np.min(y_points):np.max(y_points),
                                            np.min(x_points):np.max(x_points)]

    # Flower Counter. Uses blob detection
    if "canola_flower_finder" in feature:
        # Calculate the Yellow-ness of the image
        # Yellow = R+G-B and clip all values so they are between 0 and 1
        yellow = np.clip((masked_images[2] + masked_images[1] - masked_images[0]), thresh, 1)

        # Use a blob detector to find the yellow flowers
        blobs_log = blob_log(yellow, max_sigma=10, num_sigma=1,
                             threshold=0.1, overlap=1)
        # Compute radii in the 3rd column. which is sigma*sqrt(2)
        blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2)

        # convert the grayscale image to RGB to highlight in color
        highlight = color.gray2rgb(yellow)

        # for each blob draw a circle around it
        for blob in blobs_log:
            y, x, r = blob
            rr, cc, val = draw.circle_perimeter_aa(int(y), int(x), int(r)*3)

            # clip values of the circle that are outside of the region of interest
            rr = np.clip(rr, 0, yellow.shape[0] - 1)
            cc = np.clip(cc, 0, yellow.shape[1] - 1)

            # Draw Circles
            highlight[rr, cc] = [1,0,0]

        # save the image with highlights and the total number of flowers found
        result["canola_flower_finder"] = highlight
        result["canola_flower_count"] = blobs_log.shape[0]

    # NDVI feature calculation
    if "NDVI" or "NDVI_hist" in feature:
        num = np.subtract(masked_images[3], masked_images[2])
        dnm = np.add(masked_images[3], masked_images[2])

        NDVI = np.divide(num, dnm)
        NDVI[NDVI < thresh] = 0

        if "NDVI" in feature:
            result["NDVI"] = NDVI
        if "NDVI_hist" in feature:
            tmp, _ = np.histogram(NDVI)
            result["NDVI_hist"] = tmp


    # Calculate the greeness, which is on a scale of 0 to 1
    if "greeness" or "greeness_hist" in feature:
        grn = masked_images[1]/(masked_images[0] + masked_images[1] + masked_images[2])
        grn[grn < thresh] = 0
        if "greeness" in feature:
            result["greeness"] = grn
        if "greeness_hist" in feature:
            result["greeness_hist"] = np.histogram(grn)

    # Blue Channel
    if ("blue" or "blue_hist") in feature:
        if "blue" in feature:
            result["blue"] = masked_images[0]
        if "blue_hist" in feature:
            tmp, _ = np.histogram(masked_images[0])
            result["blue_hist"] = tmp

    # Green Channel
    if ("green" or "green_hist") in feature:
        if "green" in feature:
            result["green"] = masked_images[1]
        if "green_hist" in feature:
            tmp, _ = np.histogram(masked_images[1])
            result["green_hist"] = tmp

    # Red Channel
    if ("red" or "red_hist") in feature:
        if "red" in feature:
            result["red"] = masked_images[2]
        if "red_hist" in feature:
            tmp, _ = np.histogram(masked_images[2])
            result["red_hist"] = tmp

    # Near Infa-Red Channel
    if ("nir" or "nir_hist") in feature:
        if "nir" in feature:
            result["nir"] = masked_images[3]
        if "nir_hist" in feature:
            tmp, _ = np.histogram(masked_images[3])
            result["nir_hist"] = tmp

    # Red-edge Channel
    if ("red_edge" or "red_edge_hist") in feature:
        if "red_edge" in feature:
            result["red_edge"] = masked_images[4]
        if "red_edge_hist" in feature:
            tmp, _ = np.histogram(masked_images[4])
            result["red_edge_hist"] = tmp

    # Create an RGB image
    if ("rgb" or "RGB") in feature:
        rgb = np.dstack((masked_images[2],
                         masked_images[1],
                         masked_images[0]))
        result["rgb"] = rgb

    return result
Exemple #35
0
    def sample_lines(self, n):
        """
        Create new input images of random line segments and distractors along with ground truth parameters.

        :param n: number of images to create
        """

        data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32)
        data.fill(self.bg_clr)
        labels = np.ndarray((n, 2, 1, 1), dtype=np.float32)

        for i in range(0, n):  # for each image

            # create a random number of distractor circles
            nC = random.randint(2, 5)
            for c in range(0, nC):
                cR = random.randint(int(0.1 * self.imgW), int(1 * self.imgW))
                cX1 = random.randint(int(-0.5 * cR),
                                     int(self.imgW + 0.5 * cR + 1))
                cY1 = random.randint(int(-0.5 * cR),
                                     int(self.imgH + 0.5 * cR + 1))

                clr = (random.uniform(0, 1), random.uniform(0, 1),
                       random.uniform(0, 1))

                rr, cc, val = circle_perimeter_aa(cY1, cX1, cR)
                set_color(data[i], (rr, cc), clr, val)

            # create line segment
            while True:

                # sample segment end points
                lX1 = random.randint(self.margin, self.imgW - self.margin + 1)
                lX2 = random.randint(self.margin, self.imgW - self.margin + 1)
                lY1 = random.randint(self.margin, self.imgH - self.margin + 1)
                lY2 = random.randint(self.margin, self.imgH - self.margin + 1)

                # check min length
                length = math.sqrt((lX1 - lX2) * (lX1 - lX2) + (lY1 - lY2) *
                                   (lY1 - lY2))
                if length < minLength: continue

                # random color
                clr = (random.uniform(0, 1), random.uniform(0, 1),
                       random.uniform(0, 1))

                # calculate line ground truth parameters
                delta = lX2 - lX1
                if delta == 0: delta = 1

                slope = (lY2 - lY1) / delta
                intercept = lY1 - slope * lX1

                # not too steep for stability
                if abs(slope) < maxSlope: break

            labels[i, 0] = intercept / self.imgH
            labels[i, 1] = slope

            self.draw_line(data[i], lX1, lY1, lX2, lY2, clr)

            # apply some noise on top
            data[i] = random_noise(data[i], mode='speckle')

        return data, labels
img[rr, cc, :] = (1, 0, 1)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=-math.pi / 4.)
img[rr, cc, :] = (0, 0, 1)
rr, cc = ellipse_perimeter(120, 400, 60, 20, orientation=math.pi / 2.)
img[rr, cc, :] = (1, 1, 1)

ax1.imshow(img)
ax1.set_title('No anti-aliasing')
ax1.axis('off')


from skimage.draw import line_aa, circle_perimeter_aa


img = np.zeros((100, 100), dtype=np.double)

# anti-aliased line
rr, cc, val = line_aa(12, 12, 20, 50)
img[rr, cc] = val

# anti-aliased circle
rr, cc, val = circle_perimeter_aa(60, 40, 30)
img[rr, cc] = val


ax2.imshow(img, cmap=plt.cm.gray)
ax2.set_title('Anti-aliasing')
ax2.axis('off')

plt.show()