Exemplo n.º 1
0
    def setUp(self):
        # We create an artificial lf
        imgs = np.zeros((50,100,150), dtype=np.uint8)
        for i in range(50):
            for j in range(2):
                rr, cc = line(0, 10+j+i, 99, 10+j+i)
                imgs[i, rr, cc] = 75
            for j in range(5):
                rr, cc = line(0, 12+j+i, 99, 12+j+i)
                imgs[i, rr, cc] = 125
            for j in range(2):
                rr, cc = line(0, 17+j+i, 99, 17+j+i)
                imgs[i, rr, cc] = 75
            for j in range(5):
                rr, cc = line(0, 20+j+2*i, 99, 20+j+2*i)
                imgs[i, rr, cc] = 175
            for j in range(10):
                rr, cc = line(0, 35+j+2*i, 99, 35+j+2*i)
                imgs[i, rr, cc] = 250
            #ski.io.imsave("img_{i}.png".format(i=i), imgs[i])

        # We create epis out of it
        self.epis = np.zeros((100,50,150), dtype=np.uint8)
        for i in range(100):
            self.epis[i] = np.reshape(imgs[:,i], (50,150))
            #ski.io.imsave("epi_{i}.png".format(i=i), epis[i])
        self.epi = self.epis[25]
def add_rectangle(img, y0, x0, y1, x1, color="r", width=1):
    """Colors: 'r', 'g', 'b', 'w', 'k'"""
    im = np.copy(img)
    if im.ndim == 2:
        im = gray2rgb(im)
    max_val = 1
    if np.max(img) > 1:
        max_val = 255

    channel = 3  # Bogus value when color = 'w' or 'k'
    if color == "r":
        channel = 0
    if color == "g":
        channel = 1
    if color == "b":
        channel = 2

    for i in range(width):
        yy0 = y0 + i
        xx0 = x0 + i
        yy1 = y1 - i
        xx1 = x1 - i
        rr, cc = line(yy0, xx0, yy1, xx0)  # left
        im = paint_line(im, rr, cc, color, channel, max_val)
        rr, cc = line(yy1, xx0, yy1, xx1)  # bottom
        im = paint_line(im, rr, cc, color, channel, max_val)
        rr, cc = line(yy1, xx1, yy0, xx1)  # right
        im = paint_line(im, rr, cc, color, channel, max_val)
        rr, cc = line(yy0, xx1, yy0, xx0)  # top
        im = paint_line(im, rr, cc, color, channel, max_val)

    return im
Exemplo n.º 3
0
def drawBounds(img, boxes):
    outimg = np.zeros((img.shape[0], img.shape[1], 3))
    outimg[:,:]=[255,255,255]
    outimg[~img]=[0,0,0]
    
    for box in boxes:
        if abs(box.x1-box.x2) < 10 or abs(box.y1-box.y2) < 15:
            continue
        
        rr,cc = line(box.x1, box.y1, box.x1, box.y2)
        try:
            outimg[cc,rr]=[255,0,0]
        except IndexError:
            pass
        rr,cc = line(box.x1, box.y1, box.x2, box.y1)
        try:
            outimg[cc,rr]=[255,0,0]
        except IndexError:
            pass
        rr,cc = line(box.x1, box.y2, box.x2, box.y2)
        try:
            outimg[cc,rr]=[255,0,0]
        except IndexError:
            pass
        rr,cc = line(box.x2, box.y1, box.x2, box.y2)
        try:
            outimg[cc,rr]=[255,0,0]
        except IndexError:
            pass
    return outimg
Exemplo n.º 4
0
def test_skeletonize_num_neighbours():
    # an empty image
    image = np.zeros((300, 300))

    # foreground object 1
    image[10:-10, 10:100] = 1
    image[-100:-10, 10:-10] = 1
    image[10:-10, -100:-10] = 1

    # foreground object 2
    rs, cs = draw.line(250, 150, 10, 280)
    for i in range(10):
        image[rs + i, cs] = 1
    rs, cs = draw.line(10, 150, 250, 280)
    for i in range(20):
        image[rs + i, cs] = 1

    # foreground object 3
    ir, ic = np.indices(image.shape)
    circle1 = (ic - 135)**2 + (ir - 150)**2 < 30**2
    circle2 = (ic - 135)**2 + (ir - 150)**2 < 20**2
    image[circle1] = 1
    image[circle2] = 0
    result = skeletonize_3d(image)

    # there should never be a 2x2 block of foreground pixels in a skeleton
    mask = np.array([[1,  1],
                     [1,  1]], np.uint8)
    blocks = ndi.correlate(result, mask, mode='constant')
    assert_(not np.any(blocks == 4))
Exemplo n.º 5
0
def houghLines(img):
    w,h = img.shape
    acc=[]
    for i in range(h):
        rr,cc = line(0, i, w-1, h-i-1)
        acc.append(np.sum(img[rr, cc]))
        #print acc[i]
    mi = np.argmax(acc)
    ret = np.zeros(img.shape, dtype=np.bool)
    rr,cc = line(0, mi, w-1, h-mi-1)
    ret[rr,cc]=True
    return ret
Exemplo n.º 6
0
def display_triangle(im, tr, col):
    rows, cols = im.shape
    rr, cc = line(*map(int, tr[0]), *map(int, tr[1]))
    ind = logical_and.reduce((rr >= 0, rr < rows, cc >= 0, cc < cols))
    rr, cc = rr[ind], cc[ind]
    im[rr, cc] = col
    rr, cc = line(*map(int, tr[1]), *map(int, tr[2]))
    ind = logical_and.reduce((rr >= 0, rr < rows, cc >= 0, cc < cols))
    rr, cc = rr[ind], cc[ind]
    im[rr, cc] = col
    rr, cc = line(*map(int, tr[2]), *map(int, tr[0]))
    ind = logical_and.reduce((rr >= 0, rr < rows, cc >= 0, cc < cols))
    rr, cc = rr[ind], cc[ind]
    im[rr, cc] = col
Exemplo n.º 7
0
def draw_hough_line(image, dist, theta, color=0):
    """
    Draws a line described by the hough transform to an image

    :param image: Image to draw on
    :param dist: Hough transform distance
    :param theta: Hough transform angle
    :param color: intensity to draw line
    """

    rows, cols = image.shape

    if abs(theta) < pi/4:
        # Find the x (col) intercepts
        x0 = int_(dist/cos(theta))
        x1 = int_(x0 - rows * sin(theta))
        intercepts = (0, x0, rows, x1)

    else:
        # Find the y (row) intercepts
        y0 = int_(dist/sin(theta))
        y1 = int_(y0 + cols * cos(theta))
        intercepts = (y0, 0, y1, cols)

    r, c = line(*intercepts)

    # Check to make sure each point stays in the image bounds and draw it
    for n in range(r.size):
        if r[n] >= 0 and c[n] >= 0:
            if r[n] < rows and c[n] < cols:
                image[r[n], c[n]] = color
def display_edges(image, g, threshold):
    """Draw edges of a RAG on its image
 
    Returns a modified image with the edges drawn.Edges are drawn in green
    and nodes are drawn in yellow.
 
    Parameters
    ----------
    image : ndarray
        The image to be drawn on.
    g : RAG
        The Region Adjacency Graph.
    threshold : float
        Only edges in `g` below `threshold` are drawn.
 
    Returns:
    out: ndarray
        Image with the edges drawn.
    """
    image = image.copy()
    for edge in g.edges_iter():
        n1, n2 = edge
 
        r1, c1 = map(int, rag.node[n1]['centroid'])
        r2, c2 = map(int, rag.node[n2]['centroid'])
 
        line  = draw.line(r1, c1, r2, c2)
        circle = draw.circle(r1,c1,2)
 
        if g[n1][n2]['weight'] < threshold :
            image[line] = 0,1,0
        image[circle] = 1,1,0

    return image
Exemplo n.º 9
0
def line_image(shape, lines):
    image = np.zeros(shape, dtype=bool)
    for end_points in lines:
        # hough lines returns (x, y) points, draw.line wants (row, columns)
        end_points = np.asarray(end_points)[:, ::-1]
        image[draw.line(*np.ravel(end_points))] = 1
    return image
Exemplo n.º 10
0
def removeChessboard(img):

    # Get the major lines in the image
    edges, dilatedEdges, (h, theta, d) = findLines(img)

    # Create image with ones to fill inn lines
    lines = np.ones(img.shape[:2])

    # Add lines to image as zeroes
    for _, angle, dist in zip(*hough_line_peaks(h, theta, d)):
        y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)
        y1 = (dist - img.shape[1] * np.cos(angle)) / np.sin(angle)
        x, y = line(int(y1), 0, int(y0), img.shape[1] - 1)
        x = np.clip(x, 0, img.shape[0] - 1)
        y = np.clip(y, 0, img.shape[1] - 1)
        lines[x, y] = 0

    # Remove border edges from image with all edges
    w = 4
    edges = np.pad(edges[w:img.shape[0] - w, w:img.shape[1] - w], w, mode='constant')

    # Erode the lines bigger, such that they cover the original lines
    lines = erosion(lines, square(13))

    # Remove major lines and close shape paths
    removedChessboard = closing(edges * lines, square(8))

    return removedChessboard
Exemplo n.º 11
0
def polygon_perimeter(polygon, img_side=28):
    """
    Generate the perimeter of a polygon including the vertices.
    """
    # Create empty image
    img_shape = [img_side, img_side]
    img = np.zeros(img_shape, dtype=np.float32)

    prev_idx, cur_idx = -1, 0
    poly_len = len(polygon)
    while cur_idx < poly_len:
        # Get vertices
        prev_vertex = polygon[prev_idx]
        cur_vertex = polygon[cur_idx]

        # Get line pixels
        prev_rr, prev_cc = draw.line(
            prev_vertex[1], prev_vertex[0],
            cur_vertex[1], cur_vertex[0]
        )
        # Draw lines
        img[prev_rr, prev_cc] = 1.

        # Increment prev_idx and cur_idx
        prev_idx += 1
        cur_idx += 1

    return img
def getRandomMotionBlurMask(extent):
    X = makeRandomWalkCurve(40, 20, 2)
    Y = smoothCurve(X, 20)
    Y = Y - np.mean(Y, 0)[None, :]
    Y = Y/np.max(Y, 0)
    Y = Y*extent
    theta = np.random.rand()*2*np.pi
    Y[:, 0] = Y[:, 0] + np.cos(theta)*np.linspace(0, extent, Y.shape[0])
    Y[:, 1] = Y[:, 1] + np.sin(theta)*np.linspace(0, extent, Y.shape[0])
    D = np.sum(Y**2, 1)[:, None]
    D = D + D.T - 2*Y.dot(Y.T)
    D[D < 0] = 0
    D = 0.5*(D + D.T)
    D = np.sqrt(D)
    Y = Y*extent/np.max(D)
    Y = Y - np.mean(Y, 0)[None, :]
    Y = Y - np.min(Y)
    I = np.zeros((extent, extent))
    for i in range(Y.shape[0]-1):
        c = [Y[i, 0], Y[i, 1], Y[i+1, 0], Y[i+1, 1]]
        c = [int(np.round(cc)) for cc in c]
        rr, cc = line(c[0], c[1], c[2], c[3])
        rr = [min(max(rrr, 0), extent-1) for rrr in rr]
        cc = [min(max(ccc, 0), extent-1) for ccc in cc]
        I[rr, cc] += 1.0
    I = I/np.sum(I)
    return (Y, I)
Exemplo n.º 13
0
def draw_tile_layout(image, tiles, color=1):
    """
    Draw the tile edges on a copy of image. Make a dot at each tile center.

    This is a utility for inspecting a tile layout, not a necessary step in
    the mosaic-building process.

    Parameters
    ----------
    image : array
    tiles : list
        list of pairs of slices, as generated by :func:`partition`
    color : int or array
        value to "draw" onto ``image`` at tile boundaries

    Returns
    -------
    annotated_image : array
    """
    annotated_image = copy.deepcopy(image)
    for y, x in tqdm(tiles):
        edges = (
            (y.start, x.start, y.stop - 1, x.start),
            (y.stop - 1, x.start, y.stop - 1, x.stop - 1),
            (y.stop - 1, x.stop - 1, y.start, x.stop - 1),
            (y.start, x.stop - 1, y.start, x.start),
        )
        for edge in edges:
            rr, cc = draw.line(*edge)
            annotated_image[rr, cc] = color  # tile edges
            annotated_image[_tile_center((y, x))] = color  # dot at center
    return annotated_image
Exemplo n.º 14
0
def draw_keypoints(img, keypoints, draw_prob):
    """Draws for each keypoint a circle (roughly matching the sigma of the scale)
    with a line for the orientation.
    Args:
        img    The image to which to add the keypoints (gets copied)
        keypoints The keypoints to draw
        draw_prob Probability of drawing a keypoint (the lower the less keypoints are drawn)
    Returns:
        Image with keypoints"""
    height, width = img.shape
    img = np.copy(img)

    # convert from grayscale image to RGB so that keypoints can be drawn in red
    img = img[:, :, np.newaxis]
    img = np.repeat(img, 3, axis=2)

    for (y, x), orientation, scale_idx, scale_size, kp_type in keypoints:
        if draw_prob < 1.0 and random.random() <= draw_prob:
            # draw the circle
            radius = int(scale_size)
            rr, cc = draw.circle_perimeter(y, x, radius, shape=img.shape)
            img[rr, cc, 0] = 1.0
            img[rr, cc, 1:] = 0

            # draw orientation
            orientation = util.quantize(orientation, [-135, -90, -45, 0, 45, 90, 135, 180])
            x_start = x
            y_start = y
            if orientation == 0:
                x_end = x + radius
                y_end = y
            elif orientation == 45:
                x_end = x + radius*(1/math.sqrt(2))
                y_end = y + radius*(1/math.sqrt(2))
            elif orientation == 90:
                x_end = x
                y_end = y + radius
            elif orientation == 135:
                x_end = x - radius*(1/math.sqrt(2))
                y_end = y - radius*(1/math.sqrt(2))
            elif orientation == 180:
                x_end = x - radius
                y_end = y
            elif orientation == -135:
                x_end = x - radius*(1/math.sqrt(2))
                y_end = y - radius*(1/math.sqrt(2))
            elif orientation == -90:
                x_end = x
                y_end = y - radius
            elif orientation == -45:
                x_end = x + radius*(1/math.sqrt(2))
                y_end = y - radius*(1/math.sqrt(2))
            x_end = np.clip(x_end, 0, width-1)
            y_end = np.clip(y_end, 0, height-1)
            rr, cc = draw.line(int(y_start), int(x_start), int(y_end), int(x_end))
            img[rr, cc, 0] = 1.0
            img[rr, cc, 1:] = 0
    img = np.clip(img, 0, 1.0)

    return img
Exemplo n.º 15
0
	def footprint_fitness_error(self, points):
		temp_footprint = np.zeros(self.FOOTPRINT_added_boundary.shape, dtype=np.uint8)
		len_points = len(points)

		for idx1 in xrange(0, len_points):
			rr,cc = line(points[idx1][0], points[idx1][1], points[idx1-1][0],points[idx1-1][1])
			temp_footprint[rr,cc] = 1

		temp_footprint = ndimage.binary_fill_holes(temp_footprint)
		temp_footprint = temp_footprint * 1

		rr,cc = np.nonzero(temp_footprint)
		
		#RATIO OF ZEROS AND ONES SA LOOB
		zero_counter = 0.0
		nonzero_counter = 0.0
		for point in zip(rr,cc):
			if self.FOOTPRINT_added_boundary[point[0]][point[1]] == 0:
				zero_counter += 1.0
			else:
				nonzero_counter += 1.0

		footprint_copy = copy.deepcopy(self.FOOTPRINT_added_boundary)
		footprint_copy[rr,cc] = 0

		nonzero = len(footprint_copy[footprint_copy != 0])
		total = (len(footprint_copy[footprint_copy == 0]) + nonzero) * 1.0

		return (nonzero / total) + (zero_counter / (nonzero_counter + zero_counter))
Exemplo n.º 16
0
	def remove_deep_points(self, CIRCLE_RADIUS = 5, MINIMUM_BOUNDARY = 70):
		for point in self.POINTS_initial:
			segments = []
			circle_x, circle_y = circle_perimeter(point[0],point[1],CIRCLE_RADIUS)
			circle_points = np.array(list(sorted(set(zip(circle_x,circle_y)))))

			sortedpoints = np.empty([len(circle_points), 2], dtype=int)

			test1 = circle_points[circle_points[:,0] == point[0] - CIRCLE_RADIUS]
			start = len(test1)
			end = len_cpoints = len(sortedpoints)
			sortedpoints[0:start] = test1

			for x in xrange(point[0] - CIRCLE_RADIUS + 1, point[0] + CIRCLE_RADIUS):
				test1 = circle_points[circle_points[:,0] == x]
				testlen = len(test1)
				if x <= point[0]:
					sortedpoints[start:start+testlen/2] = test1[testlen/2:]
					sortedpoints[end-testlen/2:end] = test1[:testlen/2]
				else:
					sortedpoints[start:start+testlen/2] = test1[testlen/2:][::-1]
					sortedpoints[end-testlen/2:end] = test1[:testlen/2][::-1]
				start += testlen/2
				end -= testlen/2

			test1 = circle_points[circle_points[:,0] == point[0] + CIRCLE_RADIUS]
			sortedpoints[start:start + len(test1)] = test1[::-1]

			for c_perimeter in sortedpoints:
				segments.append(True)
				line_x, line_y = line(point[0], point[1], c_perimeter[0], c_perimeter[1])
				for line_points in zip(line_x,line_y)[1:]:
					# if original_image[line_points[0]][line_points[1]] != 0:
					if self.FOOTPRINT_cleaned_opening[line_points[0]][line_points[1]] != 0:
						segments[-1] = False
						break

			min_boundpoints = (MINIMUM_BOUNDARY / 360.0) * len_cpoints

			seg_sizes = []
			new_segment = True
			for segment in segments:
				if segment:
					if new_segment:
						seg_sizes.append(1)
						new_segment = False
					else:
						seg_sizes[-1] += 1
				else:
					new_segment = True

			if segments[0] == True and segments[-1] == True and len(seg_sizes) > 1:
				seg_sizes[0] = seg_sizes[0] + seg_sizes[-1]
				seg_sizes.pop()
			
			if(len(seg_sizes) == 0 or max(seg_sizes) < min_boundpoints):
				# boundary_image[point[0]][point[1]] = 0							#TAMA BANG TANGGALIN?

				if (point[0],point[1]) in self.POINTS_ordered:  ## IDENTIFY KUNG BAKIT NAGKA-ERRROR, EXAMPLE pt000120_merged4.py obj 1301
					self.POINTS_ordered.remove((point[0],point[1]))
Exemplo n.º 17
0
def lines(end_points, shape):
    """
    Parameters
    ----------
    end_points : iterable
        coordinates of the starting point and the ending point of each
        line: e.g., [(start_x, start_y, end_x, end_y), (x1, y1, x2, y2)]
    shape : tuple
        Image shape which is used to determine the maximum extent of output
        pixel coordinates. Order is (rr, cc).

    Returns
    -------
    label_array : array
        Elements not inside any ROI are zero; elements inside each
        ROI are 1, 2, 3, corresponding to the order they are specified
        in coords. Order is (rr, cc).

    """
    label_array = np.zeros(shape, dtype=np.int64)
    label = 0
    for points in end_points:
        if len(points) != 4:
            raise ValueError("end points should have four number of"
                             " elements, giving starting co-ordinates,"
                             " ending co-ordinates for each line")
        rr, cc = line(np.max([points[0], 0]), np.max([points[1], 0]),
                      np.min([points[2], shape[0]-1]),
                      np.min([points[3], shape[1]-1]))
        label += 1
        label_array[rr, cc] = label
    return label_array
Exemplo n.º 18
0
    def output(self):
        """Return the drawn line and the resulting scan.

        Returns
        -------
        line_image : (M, N) uint8 array, same shape as image
            An array of 0s with the scanned line set to 255.
            If the linewidth of the line tool is greater than 1,
            sets the values within the profiled polygon to 128.
        scan : (P,) or (P, 3) array of int or float
            The line scan values across the image.
        """
        end_points = self.line_tool.end_points
        line_image = np.zeros(self.image_viewer.image.shape[:2],
                              np.uint8)
        width = self.line_tool.linewidth
        if width > 1:
            rp, cp = measure.profile._line_profile_coordinates(
                *end_points[:, ::-1], linewidth=width)
            # the points are aliased, so create a polygon using the corners
            yp = np.rint(rp[[0, 0, -1, -1],[0, -1, -1, 0]]).astype(int)
            xp = np.rint(cp[[0, 0, -1, -1],[0, -1, -1, 0]]).astype(int)
            rp, cp = draw.polygon(yp, xp, line_image.shape)
            line_image[rp, cp] = 128
        (x1, y1), (x2, y2) = end_points.astype(int)
        rr, cc = draw.line(y1, x1, y2, x2)
        line_image[rr, cc] = 255
        return line_image, self.scan_data
Exemplo n.º 19
0
def p7(img, hough_img, hough_threshold):

    hough_img[hough_img < hough_threshold] = 0

    img_height, img_width = thresholded_edge_img.shape

    theta_ind = np.linspace(-pi/2, pi/2, AMOUNT_OF_BINS_THETA)
    ro_ind, step = np.linspace(0, np.sqrt(img_height**2 + img_width**2), AMOUNT_OF_BINS_RO, retstep=True)

    theta_ar, ro_ar = hough_img.nonzero()

    plt.imshow(thresholded_edge_img)
    plt.autoscale(False)

    for line_num in xrange(len(theta_ar)):

        theta = theta_ind[theta_ar[line_num]]
        ro = ro_ind[ro_ar[line_num]]

        tang = sin(theta) / cos(theta)

        b = ro / cos(theta)

        y_pos = img_width*tang + b
        y_neg = b

        try:
            coords_one, coords_two = line(0, int(y_neg), img_width, int(y_pos))
        except:
            continue
        pairs = zip(coords_two, coords_one)

        line_started = False

        for r, c in pairs:

            #print line_started

            smaller_check = r >= 0 and c >= 0
            bigger_check = r < img_height and c < img_width

            if not (smaller_check and bigger_check):
                continue

            if thresholded_edge_img[r, c] and (not line_started):
                line_started = True
                thresholded_edge_img[r, c] = 10000
                plt.plot(c, r, 'ro')
                continue

            if (not thresholded_edge_img[r, c]) and line_started:
                line_started = False
                thresholded_edge_img[r, c] = 10000
                plt.plot(c, r, 'ro')
                continue

        plt.plot([0, img_width], [y_neg, y_pos], color='r', linestyle='-', linewidth=1)

    plt.show()
Exemplo n.º 20
0
    def _calculate_spacing(self, im):
        h, w, d = im.shape
#         cw, ch = 600, 600
        cw, ch = 300, 300
        cx = (w - cw) / 2
        cy = (h - ch) / 2
        im = crop(im, cx, cy, cw, ch)
#         d = self.test_image.plotdata.get_data('imagedata000')
        d = grayspace(im)
#         d /= 255.
#         edges = filter.canny(d, sigma=3,
# #                              low_threshold=0,
# #                              high_threshold=
#                              )
#         edges = edges.astype('uint8')
#         edges = vsobel(d)
        edges = sobel(d)

        nim = zeros_like(edges)
        nim[edges > 0.1] = 255
        edges = nim
        self.test_image.set_image(edges)


        hspace, angles, dists = hough_line(edges)

        self.test_image.set_image(hspace, 1)

        _hspace, angles, dists = hough_peaks(hspace, angles, dists,

                                             )
        nim = zeros_like(edges)
        h, w, d = im.shape
        xs = []

        for ti, di in zip(angles, dists):
            ai = math.degrees(ti) + 180
            di = abs(int(round(di)))
            aa = abs(ai - 90) < 1
            bb = abs(ai - 270) < 1
            if aa or bb :
                adi = abs(di)
                coords = line(0, adi, h - 1, adi)
                nim[coords] = 200
                xs.append(di)

        self.test_image.set_image(nim, 2)
        xs.sort()
        # compute difference between each pair
        dxs = diff(xs)
        print dxs
        dd = sorted(dxs)[1:]
        print dd
        while len(dd):
            if std(dd) < 3:
                print dd
                return mean(dd) * 4  # each bar =0.25mm
            else:
                dd = dd[:-1]
Exemplo n.º 21
0
    def draw(self,img, color=red):

        line = draw.line(self.y1, self.x1, self.y2, self.x2)
        draw.set_color(img, line, color)

        if self.cx and self.cy:
            centre = draw.circle(self.cy, self.cx, 3)
            draw.set_color(img, centre, color)
Exemplo n.º 22
0
def outline(py,px):
    """Pixels contained in polygon edge"""
    oy, ox = [], []
    for y0,x0,y1,x1 in zip(py,px,np.roll(py,1),np.roll(px,1)):
        ly,lx = line(y0,x0,y1,x1)
        oy += list(ly)
        ox += list(lx)
    return (np.array(oy,int), np.array(ox,int))
Exemplo n.º 23
0
def window(image_path):
	img = io.imread(image_path)
	h   = img.shape[0]
	w 	= img.shape[1]
	step_size=32
	for i in range(0, h, step_size):
		for j in range(0, w, step_size):
			img1 = img.copy()
			if i+step_size<h and j+step_size<w:
				rr,cc = draw.line(i,j, i,j+step_size)
				img1[rr,cc] = 1
				rr,cc = draw.line(i,j, i+step_size,j)
				img1[rr,cc] = 1
				rr,cc = draw.line(i+step_size,j, i+step_size,j+step_size)
				img1[rr,cc] = 1
				rr,cc = draw.line(i,j+step_size, i+step_size,j+step_size)
				img1[rr,cc] = 1
				ImageViewer(img1).show()
Exemplo n.º 24
0
 def getMask(self):
     from skimage.draw import line
     x=np.array([p[0] for p in self.pts], dtype=int)
     y=np.array([p[1] for p in self.pts], dtype=int)
     xx, yy = line(x[0],y[0],x[1],y[1])
     idx_to_keep = np.logical_not( (xx>=self.window.mx) | (xx<0) | (yy>=self.window.my) | (yy<0))
     xx = xx[idx_to_keep]
     yy = yy[idx_to_keep]
     return xx, yy
Exemplo n.º 25
0
def test_ellipse_perimeter_flat_zeroangle():
    # flat ellipse
    img = np.zeros((20, 18), 'uint8')
    img_ = np.zeros((20, 18), 'uint8')
    rr, cc = ellipse_perimeter(6, 7, 0, 5, 0)
    img[rr, cc] = 1
    rr, cc = line(6, 2, 6, 12)
    img_[rr, cc] = 1
    assert_array_equal(img, img_)
Exemplo n.º 26
0
def test_line_diag():
    img = np.zeros((5, 5))

    rr, cc = line(0, 0, 4, 4)
    img[rr, cc] = 1

    img_ = np.eye(5)

    assert_array_equal(img, img_)
Exemplo n.º 27
0
def test_line_reverse():
    img = np.zeros((10, 10))

    rr, cc = line(0, 9, 0, 0)
    img[rr, cc] = 1

    img_ = np.zeros((10, 10))
    img_[0, :] = 1

    assert_array_equal(img, img_)
Exemplo n.º 28
0
def test_line_horizontal():
    img = np.zeros((10, 10))

    rr, cc = line(0, 0, 0, 9)
    img[rr, cc] = 1

    img_ = np.zeros((10, 10))
    img_[0, :] = 1

    assert_array_equal(img, img_)
Exemplo n.º 29
0
def test_line_vertical():
    img = np.zeros((10, 10))

    rr, cc = line(0, 0, 9, 0)
    img[rr, cc] = 1

    img_ = np.zeros((10, 10))
    img_[:, 0] = 1

    assert_array_equal(img, img_)
Exemplo n.º 30
0
def test_set_color():
    img = np.zeros((10, 10))

    rr, cc = line(0, 0, 0, 30)
    set_color(img, (rr, cc), 1)

    img_ = np.zeros((10, 10))
    img_[0, :] = 1

    assert_array_equal(img, img_)
Exemplo n.º 31
0
    def get_bresenham_paths(self, paths):
        self.bresenham_path_list = []
        for path in paths:
            points = path['points']
            bresenham_points = [None, None, None]
            for idx, point in enumerate(points):
                if idx == 0:
                    prev_point = point
                else:
                    current_point = point
                    xx, yy = line(int(prev_point[0]), int(prev_point[1]),
                                  int(current_point[0]), int(current_point[1]))
                    if bresenham_points[0] is None:
                        bresenham_points[0] = xx
                    else:
                        bresenham_points[0] = np.hstack(
                            (bresenham_points[0], xx))
                    if bresenham_points[1] is None:
                        bresenham_points[1] = yy
                    else:
                        bresenham_points[1] = np.hstack(
                            (bresenham_points[1], yy))

                    # angle calculation
                    angle_deg = self.calc_angle(prev_point, current_point)
                    if (idx < len(points) - 1):
                        next_point = points[idx + 1]
                        next_angle_deg = self.calc_angle(
                            current_point, next_point)
                        if np.abs(next_angle_deg - angle_deg) < 180:
                            aa = np.arange(
                                len(xx)) * (next_angle_deg -
                                            angle_deg) / len(xx) + angle_deg
                        else:
                            if (next_angle_deg - angle_deg) < 0:
                                aa = np.arange(
                                    len(xx)) * (next_angle_deg - angle_deg +
                                                360) / len(xx) + angle_deg
                            else:
                                aa = np.arange(
                                    len(xx)) * (next_angle_deg - angle_deg -
                                                360) / len(xx) + angle_deg
                    else:
                        aa = np.ones((len(xx))) * angle_deg
                    if bresenham_points[2] is None:
                        bresenham_points[2] = aa
                    else:
                        bresenham_points[2] = np.hstack(
                            (bresenham_points[2], aa))

                    prev_point = current_point

            self.bresenham_path_list.append(bresenham_points)

        return self.bresenham_path_list
Exemplo n.º 32
0
    def mouse_move(self, ips, x, y, btn, **key):
        if self.status == None and ips.mark != None:
            ips.mark = None
            ips.update()
        if not self.status in [
                'local_pen', 'local_brush', 'local_sketch', 'local_in',
                'local_out', 'move'
        ]:
            return
        img, color = ips.img, ColorManager.get_front()
        x = int(round(min(max(x, 0), img.shape[1])))
        y = int(round(min(max(y, 0), img.shape[0])))

        if self.status == 'move':
            x, y = key['canvas'].to_panel_coor(x, y)
            key['canvas'].move(x - self.oldp[0], y - self.oldp[1])
            self.oldp = x, y
            ips.update()
            print('move')
            return

        rs, cs = line(*[int(round(i)) for i in self.oldp + (y, x)])
        np.clip(rs, 0, img.shape[0] - 1, out=rs)
        np.clip(cs, 0, img.shape[1] - 1, out=cs)

        color = (np.mean(color), color)[img.ndim == 3]

        for r, c in zip(rs, cs):
            start = time()
            w = self.para['win']
            sr = (max(0, r - w), min(img.shape[0], r + w))
            sc = (max(0, c - w), min(img.shape[1], c + w))
            r, c = min(r, w), min(c, w)
            backclip = imgclip = img[slice(*sr), slice(*sc)]
            if not ips.back is None:
                backclip = ips.back.img[slice(*sr), slice(*sc)]

            if self.status == 'local_pen':
                local_pen(imgclip, r, c, self.para['r'], color)
            if self.status == 'local_brush':
                if (imgclip[r, c] - color).sum() == 0: continue
                local_brush(imgclip, backclip, r, c, color, 0, self.para['ms'])
            if self.status == 'local_in':
                local_in_fill(imgclip, r, c, self.para['r'], self.pickcolor,
                              color)
            if self.status == 'local_sketch':
                local_sketch(imgclip, r, c, self.para['r'], self.pickcolor,
                             color)
            if self.status == 'local_out':
                local_out_fill(imgclip, r, c, self.para['r'], self.pickcolor,
                               color)

        ips.mark = self.make_mark(x, y)
        self.oldp = (y, x)
        ips.update()
Exemplo n.º 33
0
def prepare_deform_slice(slice_shape, deformation_strength, iterations,
                         randomseed):
    # grow slice shape by 2 x deformation strength
    np.random.seed(randomseed)
    grow_by = 2 * deformation_strength
    #print ('sliceshape: '+str(slice_shape[0])+' growby: '+str(grow_by)+ ' strength: '+str(deformation_strength))
    shape = (slice_shape[0] + grow_by, slice_shape[1] + grow_by)
    # randomly choose fixed x or fixed y with p = 1/2
    fixed_x = np.random.random() < .5
    if fixed_x:
        x0, y0 = 0, np.random.randint(1, shape[1] - 2)
        x1, y1 = shape[0] - 1, np.random.randint(1, shape[1] - 2)
    else:
        x0, y0 = np.random.randint(1, shape[0] - 2), 0
        x1, y1 = np.random.randint(1, shape[0] - 2), shape[1] - 1

    ## generate the mask of the line that should be blacked out
    #print (shape)
    line_mask = np.zeros(shape, dtype='bool')
    rr, cc = line(x0, y0, x1, y1)
    line_mask[rr, cc] = 1

    # generate vectorfield pointing towards the line to compress the image
    # first we get the unit vector representing the line
    line_vector = np.array([x1 - x0, y1 - y0], dtype='float32')
    line_vector /= np.linalg.norm(line_vector)
    # next, we generate the normal to the line
    normal_vector = np.zeros_like(line_vector)
    normal_vector[0] = -line_vector[1]
    normal_vector[1] = line_vector[0]

    # make meshgrid
    x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))
    # generate the vector field
    flow_x, flow_y = np.zeros(shape), np.zeros(shape)

    # find the 2 components where coordinates are bigger / smaller than the line
    # to apply normal vector in the correct direction
    components, n_components = label(np.logical_not(line_mask).view('uint8'))
    assert n_components == 2, "%i" % n_components
    neg_val = components[0, 0] if fixed_x else components[-1, -1]
    pos_val = components[-1, -1] if fixed_x else components[0, 0]

    flow_x[components == pos_val] = deformation_strength * normal_vector[1]
    flow_y[components == pos_val] = deformation_strength * normal_vector[0]
    flow_x[components == neg_val] = -deformation_strength * normal_vector[1]
    flow_y[components == neg_val] = -deformation_strength * normal_vector[0]

    # generate the flow fields
    flow_x, flow_y = (x + flow_x).reshape(-1, 1), (y + flow_y).reshape(-1, 1)

    # dilate the line mask
    line_mask = binary_dilation(line_mask, iterations=iterations)  # default=10

    return flow_x, flow_y, line_mask
Exemplo n.º 34
0
def plot_deformed_lattice_on_image_with_affinity_label(lattice_pos,
                                                       ori_image,
                                                       adjacent,
                                                       save_path,
                                                       pairs,
                                                       affinity,
                                                       grid_pos,
                                                       thresh,
                                                       mask=None):

    plt.gca().invert_yaxis()
    image = ori_image.copy()
    #for edges
    for idx, p in enumerate(pairs):

        x1, y1 = grid_pos[p[0]]
        x2, y2 = grid_pos[p[1]]
        x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
        #line = draw.line(x1, y1, x2, y2)
        line = draw.line(y1, x1, y2, x2)
        pred = affinity[idx]
        if pred > thresh:
            image[line] = 0, 1, 0
        else:
            image[line] = 1, 1, 0

    fig, ax = plt.subplots(figsize=(image.shape[1] // 30,
                                    image.shape[0] // 30))
    ax.imshow(image)

    #plot control points
    x, y = np.where(adjacent != 0)
    conn = zip(x, y)

    if not mask is None:
        color = ['r' if i == 1 else 'g' for i in mask]
        size = [4 if i == 1 else 1 for i in mask]
    else:
        color = ['r' for i in range(lattice_pos.shape[0])]
        size = [1 for i in range(lattice_pos.shape[0])]

    graph = nx.Graph()
    #adding nodes/connections in the graph
    for node in range(lattice_pos.shape[0]):
        graph.add_node(node)

    graph.add_edges_from(conn)

    nx.draw(graph, [(x, y) for x, y in lattice_pos],
            node_size=size,
            ax=ax,
            node_color=color)

    plt.savefig(save_path)
    plt.close()
Exemplo n.º 35
0
def hough(img, nb_lines):
    """Applies the Hough Transformation to an image.
    Args:
        img The image
        nb_lines The number of lines to search for.
    Returns:
        Accumulator image,
        Local maxima in accumulator image,
        image with detected lines"""
    height, width = img.shape
    magnitude = grad_magnitude(img)
    mag_avg = np.average(magnitude)

    max_d = math.sqrt(height**2 + width**2)
    min_d = -max_d
    alphas = np.linspace(0, np.pi, NB_QUANTIZATION_STEPS)
    distances = np.linspace(min_d, max_d, NB_QUANTIZATION_STEPS)
    accumulator = np.zeros((NB_QUANTIZATION_STEPS, NB_QUANTIZATION_STEPS))
    for y in range(1, height - 1):
        for x in range(1, width - 1):
            if magnitude[y, x] > mag_avg:
                for alpha_idx, alpha in enumerate(alphas):
                    distance = x * math.cos(alpha) + y * math.sin(alpha)
                    distance_idx = util.quantize_idx(distance, distances)
                    accumulator[alpha_idx, distance_idx] += 1

    img_hough = np.zeros((height, width, 3))
    img_hough[:, :, 0] = np.copy(img)
    img_hough[:, :, 1] = np.copy(img)
    img_hough[:, :, 2] = np.copy(img)

    local_maxima = find_local_maxima(accumulator)
    peaks_idx = get_peak_indices(local_maxima, nb_lines)
    for value, (alpha_idx, distance_idx) in peaks_idx:
        peak_alpha_rad = alphas[alpha_idx]
        peak_distance = distances[distance_idx]

        x0 = 0
        x1 = width - 1
        y0 = (peak_distance -
              0 * np.cos(peak_alpha_rad)) / (np.sin(peak_alpha_rad) + 1e-8)
        y1 = (peak_distance -
              (width - 1) * np.cos(peak_alpha_rad)) / (np.sin(peak_alpha_rad) +
                                                       1e-8)

        y0 = np.clip(y0, 0, height - 1)
        y1 = np.clip(y1, 0, height - 1)

        rr, cc = draw.line(int(y0), int(x0), int(y1), int(x1))
        img_hough[rr, cc, 0] = 1
        img_hough[rr, cc, 1] = 0
        img_hough[rr, cc, 2] = 0

    return accumulator, local_maxima, img_hough
Exemplo n.º 36
0
def draw_line(line_params):

    x1 = int(line_params['X1'])
    y1 = int(line_params['Y1'])

    x2 = int(line_params['X2'])
    y2 = int(line_params['Y2'])

    rr, cc = line(x1, y1, x2, y2)

    return rr, cc
Exemplo n.º 37
0
def test_transpose_image():
    image = np.zeros((10, 10))

    rr, cc = line(4, 0, 4, 2)
    image[rr, cc] = 1
    rr, cc = line(3, 2, 3, 5)
    image[rr, cc] = 1
    rr, cc = line(1, 2, 8, 2)
    image[rr, cc] = 1
    rr, cc = line(1, 0, 1, 8)
    image[rr, cc] = 1

    skeleton1 = csr.Skeleton(image)
    skeleton2 = csr.Skeleton(image.T)

    assert (skeleton1.n_paths == skeleton2.n_paths)
    np.testing.assert_allclose(
        np.sort(skeleton1.path_lengths()),
        np.sort(skeleton2.path_lengths()),
    )
Exemplo n.º 38
0
        def _shape(self, init_state, state):
            init_canvas, init_position = init_state
            canvas, position = state

            drawn_canvas = np.copy(init_canvas)
            for i, vertex in enumerate(vertices[1:], start=1):
                rr, cc = line(vertices[i - 1][0], vertices[i - 1][1],
                              vertex[0], vertex[1])
                drawn_canvas[rr, cc] = 0
            return np.equal(drawn_canvas, canvas) and np.equal(
                position, init_position)
Exemplo n.º 39
0
def X_marksTspot(I, S_hit, S_miss):
    #make a color image and insert the binary image in one channel.
    I2 = Normalize(I)
    Iout = np.dstack([I2, I2, I2])

    #get hits from hit or miss
    hits = binary_hit_or_miss(
        I, structure1=S_hit,
        structure2=S_miss)  #, origin1 = (n//2, m//2), origin2 = (n//2, m//2))
    loc = np.array(np.where(hits == True))

    #draw x in red at locations for hits
    for i in range(loc.shape[1]):
        x, y = loc[:, i]
        rr, cc = line(x - 10, y - 8, x + 10, y + 8)
        Iout[rr, cc, :] = [1, 0, 0]
        rr, cc = line(x + 10, y - 8, x - 10, y + 8)
        Iout[rr, cc, :] = [1, 0, 0]

    return (Iout)
Exemplo n.º 40
0
def fitness_min_risk(grid, grid_max, path):
    # This also handles obstacle collisions as they are encoded as np.inf in the grid,
    # therefore summing with them gives np.inf as well
    risk = 0
    enc = path.enc_path
    for idx, n0 in enumerate(enc[:-1]):
        n1 = enc[idx + 1]
        l = line(n0[0], n0[1], n1[0], n1[1])
        risk += grid[l[0], l[1]].sum()

    return risk / grid_max
Exemplo n.º 41
0
def draw_lines(image, x, y, radius, n):
    tetha_step = 2 * np.pi / n
    for i in range(0, n):
        tetha = i * tetha_step
        line_len = int(radius * 0.7)
        x1 = int(x + line_len * np.sin(tetha))
        j1 = int(y + line_len * np.cos(tetha))
        rr, cc = line(x, y, x1, j1)
        if x1 >= image.shape[0] or j1 >= image.shape[1]:
            continue
        image[rr, cc] = 1
Exemplo n.º 42
0
def make_data(has_spaceship: bool = None,
              noise_level: float = 0.8,
              no_lines: int = 6,
              image_size: int = 200,
              classification=False) -> Tuple[np.ndarray, np.ndarray]:
    """ Data generator
    Args:
        has_spaceship (bool, optional): Whether a spaceship is included. Defaults to None (randomly sampled).
        noise_level (float, optional): Level of the background noise. Defaults to 0.8.
        no_lines (int, optional): No. of lines for line noise. Defaults to 6.
        image_size (int, optional): Size of generated image. Defaults to 200.
    Returns:
        Tuple[np.ndarray, np.ndarray]: Generated Image and the corresponding label
        The label parameters are x, y, yaw, x size, and y size respectively
        An empty array is returned when a spaceship is not included.
    """

    if has_spaceship is None:
        has_spaceship = np.random.choice([True, False], p=(0.8, 0.2))

    img = np.zeros(shape=(image_size, image_size))
    if classification:
        label = 0
    else:
        label = np.full(5, np.nan)

    # draw ship
    if has_spaceship:

        params = (_get_pos(image_size), _get_yaw(), _get_size(), _get_l2w(),
                  _get_t2l())
        pts, label = _make_spaceship(*params)

        if classification:
            label = 1

        rr, cc = polygon_perimeter(pts[:, 0], pts[:, 1])
        valid = (rr >= 0) & (rr < image_size) & (cc >= 0) & (cc < image_size)

        img[rr[valid], cc[valid]] = np.random.rand(np.sum(valid))

    # noise lines
    line_noise = np.zeros(shape=(image_size, image_size))
    for _ in range(no_lines):
        rr, cc = line(*np.random.randint(0, 200, size=4))
        line_noise[rr, cc] = np.random.rand(rr.size)

    # combined noise
    noise = noise_level * np.random.rand(image_size, image_size)
    img = np.stack([img, noise, line_noise], axis=0).max(axis=0)

    img = img.T  # ensure image space matches with coordinate space

    return img, label
Exemplo n.º 43
0
def integral_over_line(image, line: LineString):
    assert line.is_valid, "LineString is invalid"
    try:
        for pt0, pt1 in pairwise(line.coords):
            r0, c0, r1, c1 = np.array(list(pt0) + list(pt1)).astype(int)
            rr, cc = draw.line(r0, c0, r1, c1)
            ss = np.sum(image[rr, cc])
            return ss
    except Exception:
        logger.warning('integral_over_line measured incorrectly')
        return np.nan
Exemplo n.º 44
0
def test_bezier_segment_straight():
    image = np.zeros((200, 200), dtype=int)
    r0, r1, r2 = 50, 150, 150
    c0, c1, c2 = 50, 50, 150
    rr, cc = _bezier_segment(r0, c0, r1, c1, r2, c2, 0)
    image[rr, cc] = 1

    image2 = np.zeros((200, 200), dtype=int)
    rr, cc = line(r0, c0, r2, c2)
    image2[rr, cc] = 1
    assert_array_equal(image, image2)
Exemplo n.º 45
0
def displayVelocities(left, right, shape=(200, 200)):
    # NOTE: For display purposes only! To use as a distribution, call np.flipud
    # on the output
    r = shape[0]
    c = shape[1]
    # draw a circle representing the robot shape
    rr1, cc1 = circle(r / 2, c / 2, r / 10, shape)
    # draw lines representing the robot left wheel
    rr2, cc2 = line(r / 2, c / 4, r / 2 + int(left * 100), c / 4)
    rr3, cc3 = line(r / 2, c * 3 / 4, r / 2 + int(right * 100), c * 3 / 4)
    diff = (right - left) * 100
    avg = (right + left / 2) * 100
    rr4, cc4 = line(r / 2, c / 2, r / 2 + int(avg), c / 2 + int(diff))
    # push the drawings onto a color image
    img = np.zeros((r, c, 3), dtype=np.uint8)
    img[rr1, cc1, :2] = 255
    img[rr2, cc2, 1:] = 255
    img[rr3, cc3, 1:] = 255
    img[rr4, cc3, 1] = 255
    return np.flipud(img)
Exemplo n.º 46
0
def test_line_aa_diagonal():
    img = np.zeros((10, 10))

    rr, cc, val = line_aa(0, 0, 9, 6)
    img[rr, cc] = 1

    # Check that each pixel belonging to line,
    # also belongs to line_aa
    r, c = line(0, 0, 9, 6)
    for r_i, c_i in zip(r, c):
        assert_equal(img[r_i, c_i], 1)
Exemplo n.º 47
0
    def draw_models(self, labels, data=None, correct=None):
        '''
		Draw circles for a batch of images.
	
		labels -- circle parameters, array shape (Nx3) where 
			N is the number of images in the batch
			3 is the number of circles parameters (center x,  center y, radius)
		data -- batch of images to draw to, if empty a new batch wil be created according to the shape of labels 
			and circles will be green, circles will be blue otherwise
		correct -- array of shape (N) indicating whether a circle estimate is correct 
		'''

        n = labels.shape[0]
        if data is None:
            data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32)
            data.fill(self.bg_clr)
            clr = (0, 1, 0)
        else:
            clr = (0, 0, 1)

        for i in range(0, n):

            self.draw_circle(data[i], labels[i, 0], labels[i, 1], labels[i, 2],
                             clr)

            if correct is not None:

                # draw border green if estiamte is correct, red otherwise
                if correct[i]: borderclr = (0, 1, 0)
                else: borderclr = (1, 0, 0)

                set_color(data[i], line(0, 0, 0, self.imgW - 1), borderclr)
                set_color(data[i], line(0, 0, self.imgH - 1, 0), borderclr)
                set_color(data[i],
                          line(self.imgH - 1, 0, self.imgH - 1, self.imgW - 1),
                          borderclr)
                set_color(data[i],
                          line(0, self.imgW - 1, self.imgH - 1, self.imgW - 1),
                          borderclr)

        return data
Exemplo n.º 48
0
    def draw_models(self, labels, data=None, correct=None):
        '''
		Draw lines for a batch of images.
	
		labels -- line parameters, array shape (Nx2) where 
			N is the number of images in the batch
			2 is the number of line parameters (intercept, slope)
		data -- batch of images to draw to, if empty a new batch wil be created according to the shape of labels 
			and lines will be green, lines will be blue otherwise
		correct -- array of shape (N) indicating whether a line estimate is correct 
		'''

        n = labels.shape[0]
        if data is None:
            data = np.zeros((n, self.imgH, self.imgW, 3), dtype=np.float32)
            data.fill(self.bg_clr)
            clr = (0, 1, 0)
        else:
            clr = (0, 0, 1)

        for i in range(0, n):
            lY1 = int(labels[i, 0] * self.imgH)
            lY2 = int(labels[i, 1] * self.imgW + labels[i, 0] * self.imgH)
            self.draw_line(data[i], 0, lY1, self.imgW, lY2, clr)

            if correct is not None:

                # draw border green if estiamte is correct, red otherwise
                if correct[i]: borderclr = (0, 1, 0)
                else: borderclr = (1, 0, 0)

                set_color(data[i], line(0, 0, 0, self.imgW - 1), borderclr)
                set_color(data[i], line(0, 0, self.imgH - 1, 0), borderclr)
                set_color(data[i],
                          line(self.imgH - 1, 0, self.imgH - 1, self.imgW - 1),
                          borderclr)
                set_color(data[i],
                          line(0, self.imgW - 1, self.imgH - 1, self.imgW - 1),
                          borderclr)

        return data
Exemplo n.º 49
0
 def draw_line(self, x0y0, x1y1, color=(255, 0, 255)):
     # because Bresenham's line algorithm only works for integers we cast to int
     x0y0 = x0y0.astype(int)
     x1y1 = x1y1.astype(int)
     out = line(
         x0y0[0],
         x0y0[1],
         x1y1[0],
         x1y1[1]
     )
     # wrap around out toroidal world
     self.data[out[0] % (self.res[0] - 1), out[1] % (self.res[1] - 1)] = color
Exemplo n.º 50
0
def create_pos(input_size, noise=False):
    global count
    img = np.zeros(input_size)
    coord = [2,2,2,5]
    img[draw.line(*coord)] = 255.
    coord = [2,5,5,5]
    img[draw.line(*coord)] = 255.
    coord = [5,5,5,2]
    img[draw.line(*coord)] = 255.
    coord = [5,2,2,2]
    img[draw.line(*coord)] = 255.
    if noise:
        a = np.zeros([5,5])
        b = np.zeros([5,5])
        for m, n in product(range(5), range(5)):
            a[m,n] = np.sum(idxs[count:count+10] == [m,n])*5.
            b[m,n] = np.sum(idxsn[count:count+10] == [m,n])*5.
        count+=10
        img[3:8,3:8]-=a
        img[1:6,2:7]+=b
    return img[:,:,None]
Exemplo n.º 51
0
    def create_random_square(self, image_size, size_min, size_max):
        image = np.zeros((image_size, image_size), dtype=np.float64)
        size = np.random.randint(size_min, size_max)
        x = np.random.randint(0, image_size - size + 1)
        y = np.random.randint(0, image_size - size + 1)

        for i in range(0, size):
            rr, cr = draw.line(y, x + i, y + size - 1, x + i)
            image[rr, cr] = 1

        image = np.reshape(image, (image_size, image_size, 1))
        return image
def get_min_radius_to_edge(dist_img, start_pos, end_pos, dist_threshold=0.01):
    # get lines coordinates
    line = np.transpose(
        np.array(draw.line(start_pos[0], start_pos[1], end_pos[0],
                           end_pos[1])))
    # get dist values overlapping the line
    data = dist_img[line[:, 1], line[:, 0]]

    # find first index below threshold
    radius = np.argmax(data < dist_threshold)

    return radius
Exemplo n.º 53
0
        def _line(self, init_state, state):
            init_canvas, init_position = init_state
            canvas, position = state

            drawn_canvas = np.copy(init_canvas)
            rr, cc = line(init_position[0], init_position[1],
                          init_position[0] + direction[0],
                          init_position[1] + direction[1])
            drawn_canvas[rr, cc] = 0

            return np.equal(drawn_canvas, canvas) and np.equal(
                position, init_position + direction)
    def drawStuff(self, nLines):

        patch = numpy.zeros((self.shapeSize, self.shapeSize))

        for n in range(nLines):

            (r1, c1, r2, c2) = numpy.random.randint(self.shapeSize, size=4)
            rr, cc = draw.line(r1, c1, r2, c2)
            patch[rr, cc] = random.uniform(1 - random_pixels,
                                           1 + random_pixels)

        return patch
Exemplo n.º 55
0
    def draw_female(self,
                    color=(255, 0, 0),
                    thickness=2,
                    show_head_location=True):
        """Draws an ellipse perimeter around a female.

        Parameters
        ----------
        color : 3-tuple
            Color of ellipse outline.
        thickness : int
            Thickness of ellipse outline.
        show_head_location : bool (optional, default=True)
            If true, will draw an arrow from female's rear->head.

        Returns
        -------
        image : 3D np.ndarray of shape [arena.background_image.shape]
            Background image with female surrounded by ellipse.
        """
        image = self.arena.background_image.copy()

        # convert to color
        image = gray2rgb(image)
        assert image.dtype == np.uint8, "image is not of type uint8"

        if self.maj_ax_rad <= 1:
            return image

        rr, cc = ellipse_perimeter(
            self.center[0],
            self.center[1],
            self.min_ax_rad,
            self.maj_ax_rad,
            orientation=(self.orientation * np.pi /
                         180),  # Negating this value 
            # gives good results in test_trk_female.py
            # but leads to improperly oriented ellipse in
            # the gui display.
            shape=self.arena.background_image.shape)
        ellipse_outline_mask = np.zeros_like(self.arena.background_image)
        ellipse_outline_mask[rr, cc] = 1
        dilated_ellipse_outline = dilation(ellipse_outline_mask,
                                           disk(thickness))
        rr, cc = np.where(dilated_ellipse_outline)
        image[rr, cc, :] = color

        if show_head_location:
            rr, cc = line(self.center[0], self.center[1], self.head[0],
                          self.head[1])
            image[rr, cc] = color

        return image
def draw_a_line_on_image(inputs):
    current_x = int(round(inputs['current_mouse']['repr']['xdata']))
    current_y = int(round(inputs['current_mouse']['repr']['ydata']))
    previous_x = int(round(inputs['previous_mouse']['repr']['xdata']))
    previous_y = int(round(inputs['previous_mouse']['repr']['ydata']))
    if current_x >= 0 and current_y >= 0 and previous_x >= 0 and previous_y >= 0:
        rr, cc = line(previous_x, previous_y, current_x, current_y)
        dd = np.zeros(len(rr), dtype=np.int64)
        #print(rr.dtype, cc.dtype, dd.dtype)
        # NEED TO EITHER COPY THIS IMAGE, OR ASSUME NON-SHARING (CURRENTLY THIS HOLDS)
        inputs['accum']['repr'][cc, rr, dd] = 1.0  # 255
    return {'current_image_mouse': inputs['accum']}
Exemplo n.º 57
0
def test_hough_line_peaks():
    img = np.zeros((100, 150), dtype=int)
    rr, cc = line(60, 130, 80, 10)
    img[rr, cc] = 1

    out, angles, d = tf.hough_line(img)

    out, theta, dist = tf.hough_line_peaks(out, angles, d)

    assert_equal(len(dist), 1)
    assert_almost_equal(dist[0], 80.723, 1)
    assert_almost_equal(theta[0], 1.41, 1)
Exemplo n.º 58
0
def draw_network(network, label_image, index=1):

    nodes_coord = get_node_coord_array(network)
    label_image[nodes_coord[:, 0], nodes_coord[:, 1]] = index

    for edge in list(network.edges):
        start = list(network.nodes[edge[1]]['xy'])
        end = list(network.nodes[edge[0]]['xy'])
        line = draw.line(*(start + end))
        label_image[line] = index

    return label_image
Exemplo n.º 59
0
    def draw(self, action):
        action = np.clip(action, -1, 1)
        a = scale(action[0:3], -1, 1, 0, 1)
        b = scale(action[3:13], -1, 1, 0, config['STATE_DIM'][0] - 1)
        c = scale(action[13:14], -1, 1, 0, 4)
        action = np.concatenate([a, b, c]).reshape(config['ACTION_DIM'], )

        # Parameter Validation and noises
        action_category = np.argmax(action[0:3])
        if self.stroke_count == 0:
            axis = np.asarray(action[3:13], dtype=np.uint8) + np.int_(
                np.random.normal(0, 2, action[3:13].shape[0]))
            c_p = action[13] + np.random.normal(0, 1)
        else:
            axis = np.asarray(action[3:13], dtype=np.uint8)
            c_p = action[13]

        for i in range(axis.shape[0]):
            if axis[i] < 2:
                axis[i] = 2
            elif axis[i] >= self.dim[0] - 2:
                axis[i] = self.dim[0] - 2

        if action_category == 1:
            self.stroke_count += 1
            # Draw line
            rr, cc = line(axis[0], axis[1], axis[2], axis[3])
            self.canvas[rr, cc] = 1

        if action_category == 2:
            self.stroke_count += 1
            # Draw Curve
            try:
                rr, cc = bezier_curve(axis[4], axis[5], axis[6], axis[7],
                                      axis[8], axis[9], c_p)
            except MemoryError:
                while True:
                    try:
                        _x1, _y1 = move_point(axis[4], axis[5])
                        _x2, _y2 = move_point(axis[6], axis[7])
                        _x3, _y3 = move_point(axis[8], axis[9])
                        rr, cc = bezier_curve(_x1, _y1, _x2, _y2, _x3, _y3,
                                              c_p)
                        break
                    except MemoryError:
                        continue

            try:
                self.canvas[rr, cc] = 1
            except IndexError:
                rr = np.clip(rr, 0, config['STATE_DIM'][0] - 1)
                cc = np.clip(cc, 0, config['STATE_DIM'][1] - 1)
                self.canvas[rr, cc] = 1
Exemplo n.º 60
0
    def __init__(self, point_1, point_2, point_3):
        self.line_bg_mem = line(point_1[0], point_1[1], point_2[0], point_2[1])
        self.line_cyt_sept = line(point_2[0], point_2[1], point_3[0],
                                  point_3[1])
        self.background = None
        self.membrane = None
        self.septum = None
        self.fr = None

        self.image = None

        x_points = []
        x_points.extend(self.line_bg_mem[0])
        x_points.extend(self.line_cyt_sept[0])

        y_points = []
        y_points.extend(self.line_bg_mem[1])
        y_points.extend(self.line_cyt_sept[1])

        self.box = min(x_points) - 10, min(y_points) - \
            10, max(x_points) + 10, max(y_points) + 10