示例#1
0
def test_set_color_with_alpha():
    img = np.zeros((10, 10))

    rr, cc, alpha = line_aa(0, 0, 0, 30)
    set_color(img, (rr, cc), 1, alpha=alpha)

    # Wrong dimensionality color
    assert_raises(ValueError, set_color, img, (rr, cc), (255, 0, 0), alpha=alpha)

    img = np.zeros((10, 10, 3))

    rr, cc, alpha = line_aa(0, 0, 0, 30)
    set_color(img, (rr, cc), (1, 0, 0), alpha=alpha)
示例#2
0
def test_line_equal_aliasing_horizontally_vertically():
    img0 = np.zeros((25, 25))
    img1 = np.zeros((25, 25))

    # Near-horizontal line
    rr, cc, val = line_aa(10, 2, 12, 20)
    img0[rr, cc] = val

    # Near-vertical (transpose of prior)
    rr, cc, val = line_aa(2, 10, 20, 12)
    img1[rr, cc] = val

    # Difference - should be zero
    assert_array_equal(img0, img1.T)
示例#3
0
def test_line_aa_horizontal():
    img = np.zeros((10, 10))

    rr, cc, val = line_aa(0, 0, 0, 9)
    set_color(img, (rr, cc), 1, alpha=val)

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

    assert_array_equal(img, img_)
示例#4
0
def test_line_aa_horizontal():
    img = np.zeros((10, 10))

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

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

    assert_array_equal(img, img_)
示例#5
0
def test_line_aa_vertical():
    img = np.zeros((10, 10))

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

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

    assert_array_equal(img, img_)
示例#6
0
 def crop_to_sequence(self, track_list, currSharp):
     '''
     In the crop filename, I add the number of the image in the galerie so that they're by default ordered in time
     
     I need the bounding box of the membrane and also to use whitefield images.
     '''
     
     for track in track_list:
         id_=track.id
         lstFrames=sorted(track.lstPoints.keys(), key=itemgetter(0))
         rr=[]; cc=[]; val=[]; nextCoord=None
         for i, el in enumerate(lstFrames):
             im, cell_id=el
             coordonnees=track.lstPoints[(im, cell_id)] if nextCoord==None else nextCoord
             try:
                 nextCoord=track.lstPoints[lstFrames[i+1]]
             except IndexError:
                 continue
             else:
                 r,c,v=draw.line_aa(coordonnees[0], coordonnees[1],nextCoord[0], nextCoord[1])
                 rr.extend(r); cc.extend(c); val.extend(v)
                 
         for im, cell_id in lstFrames:
             #renumbering according to xb screen/PCNA image numbering
             local_im=im+1
             
             #draw a dot on the cell which is followed
             cell_x, cell_y=track.lstPoints[(im, cell_id)]
             dot_rr, dot_cc=draw.circle(cell_x, cell_y, radius=3)
                 
             image_name= self.settings.imageFilename.format(self.well, local_im)
             image=vi.readImage(os.path.join(self.settings.allDataFolder, self.plate, 'analyzed', self.well, 'images/tertiary_contours_expanded', image_name))
             
             #X,x,x__, Y,y,y__=self._newImageSize(crop_coordinates)
             x__=self.settings.XMAX; y__=self.settings.YMAX; x=0; y=0; X=self.settings.XMAX; Y=self.settings.YMAX
             
             croppedImage = VigraArray((x__, y__, 3), dtype=np.dtype('float32'))
             croppedImage=image[x:X, y:Y]  
             croppedImage[rr,cc,0]=np.array(val)*255
             
     #If there is a sharp movement, the cell center is pinky red
             if im in currSharp[id_]:
                 croppedImage[dot_rr, dot_cc, 0]=242
                 croppedImage[dot_rr, dot_cc, 1]=21
                 croppedImage[dot_rr, dot_cc, 2]=58
             else:
     #If not, it is green
                 croppedImage[dot_rr, dot_cc, 1]=255
             
             vi.writeImage(croppedImage, \
                           os.path.join(self.outputFolder, self.plate, 'galerie',
                                        self.settings.outputImage.format(self.plate, self.well.split('_')[0],id_, im)),\
                           dtype=np.dtype('uint8'))
             
     return
示例#7
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 x, y in zip(r, c):
        assert_equal(img[r, c], 1)
示例#8
0
    def add_boundary(self, boundaries):
        """
        Add boundaries to the map.
        :param boundaries: list of tuples containing coordinates of boundaries'
        start and end points
        """

        # Extend list of boundaries
        self.boundaries.extend(boundaries)

        # Iterate over list of boundaries
        for boundary in boundaries:
            sx = self.w2m(boundary[0][0], boundary[0][1])
            gx = self.w2m(boundary[1][0], boundary[1][1])
            path_x, path_y, _ = line_aa(sx[0], sx[1], gx[0], gx[1])
            for x, y in zip(path_x, path_y):
                self.data[y, x] = 0
示例#9
0
    def __draw_line(self, new_c, new_r):
        r0 = int(round(self.__clip_coordinate(self.__r, 0)))
        c0 = int(round(self.__clip_coordinate(self.__c, 1)))
        r1 = int(round(self.__clip_coordinate(new_r, 0)))
        c1 = int(round(self.__clip_coordinate(new_c, 1)))

        if self.aa:
            rr, cc, val = line_aa(r0, c0, r1, c1)
        else:
            rr, cc = line(r0, c0, r1, c1)
            val = 1

        if self.__channels == 1:
            self.array[rr, cc] = val * self.__color
        else:
            for c in range(self.__channels):
                self.array[rr, cc, c] = val * self.__color[c]
    def _get_min_width(self, wp, t_x, t_y, max_width):
        """
        Compute the minimum distance between the current waypoint and the
        orthogonal cell on the border of the path
        :param wp: current waypoint
        :param t_x: x coordinate of border cell in map coordinates
        :param t_y: y coordinate of border cell in map coordinates
        :param max_width: maximum path width in m
        :return: min_width to border and corresponding cell
        """

        # Get neighboring cells of orthogonal cell (account for
        # discretization inaccuracy)
        tn_x, tn_y = [], []
        for i in range(-1, 2, 1):
            for j in range(-1, 2, 1):
                tn_x.append(t_x + i)
                tn_y.append(t_y + j)

        # Get pixel coordinates of waypoint
        wp_x, wp_y = self.map.w2m(wp.x, wp.y)

        # Get Bresenham paths to all possible cells
        paths = []
        for t_x, t_y in zip(tn_x, tn_y):
            x_list, y_list, _ = line_aa(wp_x, wp_y, t_x, t_y)
            paths.append(zip(x_list, y_list))

        # Compute minimum distance to border cell
        min_width = max_width
        # map inspected cell to world coordinates
        min_cell = self.map.m2w(t_x, t_y)
        for path in paths:
            for cell in path:
                t_x, t_y = cell[0], cell[1]
                # If path goes through occupied cell
                if self.map.data[t_y, t_x] == 0:
                    # Get world coordinates
                    c_x, c_y = self.map.m2w(t_x, t_y)
                    cell_dist = np.sqrt((wp.x - c_x)**2 + (wp.y - c_y)**2)
                    if cell_dist < min_width:
                        min_width = cell_dist
                        min_cell = (c_x, c_y)

        return min_width, min_cell
示例#11
0
def _render_line(canvas, curr_pos, l_args, absolute, color):
    """Renders a line in the given canvas."""
    end_point = l_args
    if not absolute:
        end_point[0] += curr_pos[0]
        end_point[1] += curr_pos[1]
    rr, cc, val = draw.line_aa(int(curr_pos[0]), int(curr_pos[1]),
                               int(end_point[0]), int(end_point[1]))

    max_possible = len(canvas)
    within_range = lambda x: 0 <= x < max_possible
    filtered = [(x, y, v) for x, y, v in zip(rr, cc, val)
                if within_range(x) and within_range(y)]
    if not filtered:
        return
    rr, cc, val = list(zip(*filtered))
    val = [(v * color) for v in val]
    canvas[cc, rr, :] = val
示例#12
0
def make_lines(nbins=9, degree_base=180, frame_size=8):
    """
    #TODO docstring
    """

    # make nbins channel image
    lines_bank = np.zeros((nbins, frame_size, frame_size), dtype=np.uint8)
    # angles by bins, convert to radians
    theta_rad = (np.arange(nbins) * (degree_base / nbins)) * (np.pi / 180)
    # line diameter
    _d = frame_size - 1
    # find m and c (y=mx+c) passing center point of visualization image (for now, using square (w=h))
    m = np.tan(theta_rad)
    c = (_d + 1 // 2) * (1 - m)

    # find max min y,x
    x_1 = np.abs(1 + (_d) // 2 * (1 + np.cos(theta_rad))).astype(np.int)
    y_1 = np.abs(1 + (_d) // 2 * (1 + np.sin(theta_rad))).astype(np.int)
    y_0 = _d - y_1
    x_0 = _d - x_1

    for i, img in enumerate(lines_bank):
        # using skimage
        # rr, cc = draw.line(x_1[i], y_0[i], x_0[i], y_1[i])
        # # x is y, y is -x (rotate by 90deg)
        # # rr, cc = draw.line(y_0[i], -x_0[i], y_1[i], -x_1[i])
        # img[rr,cc] = 255

        rr, cc, val = draw.line_aa(x_1[i], y_0[i], x_0[i], y_1[i])
        img[rr, cc] = val * 255

        # # using PIL
        # pilimg = Image.new('L', (frame_size, frame_size), 0)
        # draw = ImageDraw.Draw(pilimg)
        # # draw.line([(x_1[i], y_0[i]), (x_0[i], y_1[i])], fill=255, width=2)
        # draw.line([(y_1[i], x_0[i]), (y_0[i], x_1[i])], fill=128, width=1)
        # # print(np.asarray(pilimg).shape,img.shape)
        # img += np.asarray(pilimg)

        #DEBUG
        # plt.imshow(img)
        # plt.show()

    return lines_bank
def projection_on_magnet(ends_of_strawtubes, x_resolution=1., y_resolution=1., z_magnet=3070.):
    
    tubes = []
    
    for i in range(len(ends_of_strawtubes)):
        
        tubes.append(ends2params(ends_of_strawtubes[i]))

    lines = []
    z3 = z_magnet
    for i in range(len(tubes)):
        
        for j in range(i+1, len(tubes)):
        
            t1 = tubes[i]
            t2 = tubes[j]
            
            if (t1[2] != t2[2]) and (np.sum(t1[1] - t2[1]) < 0.01):
                
                start1 = t1[0]
                start2 = t2[0]
                z1 = t1[2]
                z2 = t2[2]
                start3 = (start2 - start1) / (z2 - z1) * (z3 - z2) + start2
                
                if (start3[1] > -500) and (start3[1] < 500) and (start3[0] < -225) and (start3[0] > -275):
                
                    lines.append([start3, t1[1]])
    
    x_len = int(600 * x_resolution)
    y_len = int(1200 * y_resolution)
    line_len = 500

    matrix = np.zeros([x_len, y_len])
    
    for line in lines:
        
        rr, cc, val = line_aa(int(round(line[0][0] * x_resolution)) + x_len / 2, int(round(line[0][1] * y_resolution)) + y_len / 2,\
                              int(round((line[0][0] + line[1][0] * line_len) * x_resolution)) + x_len / 2,\
                              int(round((line[0][1] + line[1][1] * line_len) * y_resolution)) + y_len / 2)
        matrix[rr, cc] += 1
        
    return matrix
def draw_joint(colors, pose_joints, joint_line_list, radius=2):
    im_size = (colors.shape[0], colors.shape[1])
    for f, t in joint_line_list:
        from_missing = pose_joints[0,f] == MISSING_VALUE or pose_joints[1,f] == MISSING_VALUE
        to_missing = pose_joints[0,t] == MISSING_VALUE or pose_joints[1,t] == MISSING_VALUE
        if from_missing or to_missing:
            continue
        yy, xx, val = line_aa(pose_joints[0,f], pose_joints[1,f], pose_joints[0,t], pose_joints[1,t])
        yy, xx = np.clip(yy, 0, im_size[0]-1), np.clip(xx, 0, im_size[1] - 1)
        colors[yy, xx] = np.expand_dims(val, 1) * 255
        # mask[yy, xx] = True

    colormap = labelcolormap(pose_joints.shape[1])
    for i in range(pose_joints.shape[1]):
        if pose_joints[0,i] == MISSING_VALUE or pose_joints[1,i] == MISSING_VALUE:
            continue
        yy, xx = disk((pose_joints[0,i], pose_joints[1,i]), radius=radius, shape=im_size)
        colors[yy, xx] = colormap[i]
    return colors
def projection_on_magnet(ends_of_strawtubes, x_resolution=1., y_resolution=1., z_magnet=3070.):
    
    tubes = []
    
    for i in range(len(ends_of_strawtubes)):
        
        tubes.append(ends2params(ends_of_strawtubes[i]))

    lines = []
    z3 = z_magnet
    for i in range(len(tubes)):
        
        for j in range(i+1, len(tubes)):
        
            t1 = tubes[i]
            t2 = tubes[j]
            
            if (t1[2] != t2[2]) and (np.sum(t1[1] - t2[1]) < 0.01):
                
                start1 = t1[0]
                start2 = t2[0]
                z1 = t1[2]
                z2 = t2[2]
                start3 = (start2 - start1) / (z2 - z1) * (z3 - z2) + start2
                
                if (start3[1] > -500) and (start3[1] < 500) and (start3[0] < -225) and (start3[0] > -275):
                
                    lines.append([start3, t1[1]])
    
    x_len = int(600 * x_resolution)
    y_len = int(1200 * y_resolution)
    line_len = 500

    matrix = np.zeros([x_len, y_len])
    
    for line in lines:
        
        rr, cc, val = line_aa(int(round(line[0][0] * x_resolution)) + x_len / 2, int(round(line[0][1] * y_resolution)) + y_len / 2,\
                              int(round((line[0][0] + line[1][0] * line_len) * x_resolution)) + x_len / 2,\
                              int(round((line[0][1] + line[1][1] * line_len) * y_resolution)) + y_len / 2)
        matrix[rr, cc] += 1
        
    return matrix
示例#16
0
    def get_line():
        def sample():
            r1 = int(rng.random() * image.shape[0])
            c1 = int(rng.random() * image.shape[1])
            r2 = int(rng.random() * image.shape[0])
            c2 = int(rng.random() * image.shape[1])
            return r1, c1, r2, c2

        while True:
            r1, c1, r2, c2 = sample()
            if (r1 - r2)**2 + (c1 - c2)**2 > 25:
                break

        rr, cc, val = line_aa(r1, c1, r2, c2)

        line_mask = np.zeros_like(image)
        line_mask[rr, cc] = val
        line_mask = (gaussian(line_mask, sigma=3) > 0.01)
        return line_mask
示例#17
0
def draw_random_line_aa(im, red, green, blue):

    shape = im.shape
    row_length = shape[1]
    column_length = shape[2]

    r0 = np.random.randint(0, high=row_length)
    c0 = np.random.randint(0, high=column_length)

    r1 = np.random.randint(0, high=row_length)
    c1 = np.random.randint(0, high=column_length)

    rr, cc, val = line_aa(r0, c0, r1, c1)

    im[0, rr, cc] = val * red
    im[1, rr, cc] = val * green
    im[2, rr, cc] = val * blue

    return im
示例#18
0
def draw_pols_as_lines(pols, sz = [640,640]):
	'''
	Inputs: Accepts list of polygons and a size tuple/list for output image.
	Outputs: Boolean Image of polygons lines drawn
	Example:
	>> POLS = [
					[[404, 236], [496, 357], [304, 492]], 
					[[125, 270], [157, 307], [131, 323]], 
			]
	>> draw_pols_as_lines(POLS, sz=[640,640])
	'''
	img = np.zeros(sz)
	for pol in pols:
		if pol:
			for i in range(len(pol)):
				p0, p1 = pol[i], pol[(i+1)%len(pol)]
				rr, cc, val = draw.line_aa(int(p0[0]), int(p0[1]), int(p1[0]), int(p1[1]))
				img[rr, cc] = 1
	return img.astype(bool)
示例#19
0
def drawline(theta, row_c, col_c, row, col):
    radians = math.radians(theta)

    tang = math.tan(radians)
    row_t = []
    col_t = []
    if theta == 45:
        row_t.append(0)
        row_t.append(row - 1)
        col_t.append(col - 1)
        col_t.append(0)
    if theta == 135:
        row_t.append(0)
        row_t.append(row - 1)
        col_t.append(0)
        col_t.append(col - 1)
    if theta is 90:
        row_t.append(0)
        row_t.append(row - 1)
        col_t.append(col_c)
        col_t.append(col_c)
    elif theta is 0:
        row_t.append(row_c)
        row_t.append(row_c)
        col_t.append(0)
        col_t.append(col - 1)
    else:
        row_V = tang * (col - col_c)
        col_V = (float(row_c)) / float(tang)
        if abs(row_V) > row_c:
            row_t.append(0)
            row_t.append(row - 1)
            col_t.append(col_c + int(col_V))
            col_t.append(col_c - int(col_V))
        elif abs(col_V) > col - col_c:
            col_t.append(0)
            col_t.append(col - 1)
            row_t.append(row_c + int(row_V))
            row_t.append(row_c - int(row_V))

    rr, cc, val = line_aa(row_t[0], col_t[0], row_t[1], col_t[1])
    return rr, cc
示例#20
0
def draw_lines(lines, sz=[640, 640]):
    """
        Inputs: Accepts list of lines, a line is a tuple, which contains two tuples,
        point A and point B. A size sz which is default to (640,640)
        Outputs: A Boolean Image of Lines,
        Example:
        >> lines = [
                ((10,10),(20,20)),
                ((30,30),(50,50))
        ]
        >> draw_lines(lines, sz = (100,100))
    """
    img = np.zeros(sz)
    for line in lines:
        p1, p2 = line
        r0, c0 = p1
        r1, c1 = p2
        rr, cc, val = draw.line_aa(int(c0), int(r0), int(c1), int(r1))
        img[rr, cc] = 1
    return img.astype(bool)
示例#21
0
def draw_pose_from_cords_and_visibility(pose_joints, visibility, img_size, radius=2, draw_joints=True):
    colors = np.zeros(shape=img_size + (3,), dtype=np.uint8)

    if draw_joints:
        for f, t in LIMB_SEQ:
            if _is_invalid(pose_joints[f], visibility[f]) or _is_invalid(pose_joints[t], visibility[t]):
                continue
            yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1], pose_joints[t][0], pose_joints[t][1])
            try:
                colors[yy, xx] = np.expand_dims(val, 1) * 255
            except IndexError:
                print(pose_joints[f], pose_joints[t])

    for i, joint in enumerate(pose_joints):
        if _is_invalid(pose_joints[i], visibility[i]):
            continue
        yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size)
        colors[yy, xx] = COLORS[i]

    return colors
示例#22
0
def draw_line(canvas, start, end, value=0, opacity=.6, fast=False):
    """
    In place draws a line with anti-aliasing and given opacity.

    canvas: array where to apply the line in-place.
    start: Initial row and column.
    end: Final row and column.
    value: color to paint.
    opacity: how much to affect the image with the new values.
    fast: it'll would execute a single operation, this ignores anti-alianing.
    """
    if fast:
        rr, cc = draw.line(*start, *end)
        original = canvas[rr, cc]
        canvas[rr, cc] = value * opacity + original * (1 - opacity)
    else:
        rr, cc, alpha = draw.line_aa(*start, *end)
        original = canvas[rr, cc]
        painted = value * alpha + original * (1 - alpha)
        canvas[rr, cc] = painted * opacity + original * (1 - opacity)
示例#23
0
def draw_pose_from_cords(pose_joints, img_size, target_img, radius=2, draw_joints=True):
    colors = np.zeros(shape=img_size + (3, ), dtype=np.uint8)
    colors = target_img

    if draw_joints:
        for f, t in LIMB_SEQ:
            from_missing = pose_joints[f][0] == MISSING_VALUE or pose_joints[f][1] == MISSING_VALUE
            to_missing = pose_joints[t][0] == MISSING_VALUE or pose_joints[t][1] == MISSING_VALUE
            if from_missing or to_missing:
                continue
            yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1], pose_joints[t][0], pose_joints[t][1])
            colors[yy, xx] = np.expand_dims(val, 1) * 255

    for i, joint in enumerate(pose_joints):
        if pose_joints[i][0] == MISSING_VALUE or pose_joints[i][1] == MISSING_VALUE:
            continue
        yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size)
        colors[yy, xx] = COLORS[i]

    return colors
示例#24
0
文件: piro.py 项目: sy9976/piro_proj1
def filter_contours_lines(v0, v1, lines, img, dist): #linie zaczynajace sie w danym punkcie w otoczeniu dist pikseli
  print "v0, v1:" , v0, v1
  max_line_length = 0
  for tmp_line in lines:
    tmp0, tmp1 = tmp_line
    tp0 = (tmp0[1], tmp0[0])
    tp1 = (tmp1[1], tmp1[0])
    if distance(tmp0, tmp1) > max_line_length:
      max_line_length = distance(tmp0, tmp1)
      print "NEW_MAX:", tmp0, tmp1
    print "tp0 tp1: " ,tp0, tp1
    print "v0 tp0", distance(v0, tp0)
    print "v0 tp1", distance(v0, tp1)
    print "v1 tp0", distance(v1, tp0)
    print "v1 tp1", distance(v1, tp1)
    if distance(v0, tp0) < dist or distance(v0, tp1) < dist or distance(v1, tp0) < dist or distance(v1, tp1) < dist:
      print "removing line"
      rr, cc, v = line_aa(tmp0[1], tmp0[0], tmp1[1], tmp1[0])
      img[rr,cc] = 0
  return img, max_line_length
示例#25
0
def draw_pose_from_cords(pose_joints,
                         observed,
                         img_size=(256, 256),
                         radius=2,
                         draw_joints=True,
                         img=np.zeros([224, 224, 3])):
    pose_joints = np.round(pose_joints).astype(np.int32)
    pose_joints[pose_joints < 0] = 0
    pose_joints[pose_joints > 255] = 255
    pose_joints = pose_joints.reshape([18, 2])
    colors = np.zeros(shape=img_size + (3, ), dtype=np.uint8)
    # interesting case of numpy array assignment semantics here . . the below ass is a view, hence the overliad poses error that destroyed the precious time of an incomporable specimen on this overpopulated information craving filth obsessed world
    # colors = img
    mask = np.zeros(shape=img_size, dtype=bool)

    if draw_joints:
        for f, t in LIMB_SEQ:
            from_missing = pose_joints[f][0] == MISSING_VALUE or pose_joints[
                f][1] == MISSING_VALUE or observed[f] == 0 or observed[18 +
                                                                       f] == 0
            to_missing = pose_joints[t][0] == MISSING_VALUE or pose_joints[t][
                1] == MISSING_VALUE or observed[t] == 0 or observed[18 +
                                                                    t] == 0
            if from_missing or to_missing:
                continue
            yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1],
                                  pose_joints[t][0], pose_joints[t][1])
            colors[yy, xx] = np.expand_dims(val, 1) * 255
            mask[yy, xx] = True

    for i, joint in enumerate(pose_joints):
        if pose_joints[i][0] == MISSING_VALUE or pose_joints[i][
                1] == MISSING_VALUE or observed[i] == 0 or observed[18 +
                                                                    i] == 0:
            continue
        yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size)
        colors[yy, xx] = COLORS[i]
        mask[yy, xx] = True

    # colors = colors.transpose((2,0,1))
    return colors
def draw_shape(img, shape):
    '''
    Takes in shapes as input and
    :param img: image to modify
    :param shape: shape to draw ( a series of x and y paired coordinates)
    :return: a new image that has the shape drawn
    '''
    from skimage.draw import line_aa

    # print("Drawing the next shape")
    for i in range(len(shape) - 1):
        # print("First shape x and y : " + str(shape[i]))
        # print("Second shape x and y : " + str(shape[i+1]))
        rr, cc, val = line_aa(shape[i][0], shape[i][1], shape[i + 1][0],
                              shape[i + 1][1])
        # print(val)
        # print(rr)
        # print(cc)
        img[rr, cc] = val * 255

    return img
示例#27
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
    def gen_scored_points():
        for points in itertools.combinations(intersection_points, 4):
            points = list(map(np.array, sorted(points, key=lambda x: -sum(x))))
            sorted_points = [points.pop()[:2]]
            while len(points) > 0:
                points.sort(key=lambda x: -min(
                    np.abs(np.array(x) - sorted_points[-1])))
                sorted_points.append(points.pop())

            sorted_points = [np.round(p).astype(int) for p in sorted_points]
            score = 0
            deltas = [sorted_points[0] - sorted_points[-1]]
            for i in range(4):
                p1 = sorted_points[i]
                p2 = sorted_points[(i + 1) % 4]

                delta = p2 - p1
                # filter out small edges
                # print('|delta|=',np.linalg.norm(delta))
                if np.linalg.norm(delta) < min(im_rows, im_cols) / 2:
                    score = 0
                    break

                # filter out acute angles
                angle = np.degrees(
                    np.arccos(delta @ deltas[-1] / np.linalg.norm(delta) /
                              np.linalg.norm(deltas[-1])))
                # print('angle=', angle)
                if angle < 60 or angle > 120:
                    score = 0
                    break

                rr, cc, vals = line_aa(p1[1], p1[0], p2[1], p2[0])
                ix_1 = rr < im_rows - 1
                ix_2 = cc < im_cols - 1
                ix = ix_1 * ix_2
                score += np.sum(vals[ix] * original_edged[rr[ix], cc[ix]])
                deltas.append(delta)

            yield score, sorted_points, deltas
示例#29
0
def visualize(sketch):
    assert sketch.shape[1] in [3, 5]

    # start token
    if sketch.shape[1] == 3:
        sketch = np.concatenate(([[0, 0, 0]], sketch))
    elif sketch.shape[1] == 5:
        sketch = np.concatenate(([[0, 0, 1, 0, 0]], sketch))
        length = np.where(sketch[:, 4] == 1)[0]
        if len(length) > 0:
            sketch = sketch[:length[0] + 1]

    # coordinates
    sketch[:, 0] = np.cumsum(sketch[:, 0], 0)
    sketch[:, 0] -= np.min(sketch[:, 0])

    sketch[:, 1] = np.cumsum(sketch[:, 1], 0)
    sketch[:, 1] -= np.min(sketch[:, 1])

    if np.max(sketch[:, :2]) > 0:
        sketch[:, :2] /= np.max(sketch[:, :2])
        sketch[:, :2] *= 255

    # sequence => strokes
    if sketch.shape[1] == 3:
        strokes = np.split(sketch, np.where(sketch[:, 2] == 1)[0] + 1)
    elif sketch.shape[1] == 5:
        strokes = np.split(sketch, np.where(sketch[:, 3] == 1)[0] + 1)

    # canvas
    canvas = np.ones((256, 256, 3), dtype = np.float32)
    index, length = 0, np.sum([len(stroke) - 1 for stroke in strokes])
    for stroke in strokes:
        for k in range(len(stroke) - 1):
            x1, y1 = map(int, stroke[k, :2])
            x2, y2 = map(int, stroke[k + 1, :2])
            rr, cc, _ = line_aa(y1, x1, y2, x2)
            canvas[rr, cc, :] = .75 * index / length
            index += 1
    return canvas.transpose(2, 0, 1)
示例#30
0
    def custom_train_loop(self, sess, train_targets, **loop_params):
        """Define Custom training loop.
        Args:
            sess (tf.Session): Current tensorflow session.
            train_targets (list): Description.
            **loop_params: Optional kwargs needed to perform custom train loop.
        Returns:
            dict: A dictionary containing train targets evaluated by the session.
        """
        # boxes = var_dict['boxes']
        # boxes_val = sess.run(boxes)
        # import pdb; pdb.set_trace()
        max_obj = 0
        for i in range(20):
            # ih, iw, image, obj_count, boxes = sess.run([var_dict[k] for k in  ['ih', 'iw', 'images', 'num_objects', 'boxes']]) #['images', 'labels',
            ih, iw, obj_count, boxes, images = sess.run([
                var_dict[k]
                for k in ['ih', 'iw', 'num_objects', 'boxes', 'images']
            ])
            max_obj = max(max_obj, obj_count)
            print i, ih, iw, obj_count, boxes[
                0][:obj_count[0]]  #, image.shape, obj_count

            img = np.array(images[0])
            x_center, y_center, w, h = boxes[0, 0, :4]
            coords = [(x_center - w / 2), (x_center + w / 2),
                      (y_center - h / 2), (y_center + h / 2)]  # x1, x2, y1, y2
            x1, x2, y1, y2 = [int(c) for c in coords]
            print([int(c) for c in coords])
            rr, cc, val = line_aa(y1, x1, y2, x2)
            img[rr, cc, 0] = val
            imsave('image_{}.png'.format(i), img)

        import pdb
        pdb.set_trace()
        train_results, p = sess.run([train_targets, var_dict['print']])
        for i, result in enumerate(train_results):
            print('Model {} has loss {}'.format(i, result['loss']))
        return train_results
def collect_line_coords(seg_line_df, scale=1):
    # group according to line idx
    grouped = seg_line_df.groupby('line_idx')

    # collect all line coordinates
    rr_list, cc_list, lbbox_list = [], [], []
    for i, line_rec in grouped:
        xx = np.rint(line_rec.x.values * scale).astype(int)
        yy = np.rint(line_rec.y.values * scale).astype(int)
        lbbox = np.array([np.min(xx), np.min(yy), np.max(xx), np.max(yy)])
        lbbox_list.append(lbbox)
        for li in range(len(xx) - 1):
            rr, cc, _ = line_aa(yy[li], xx[li], yy[li + 1], xx[li + 1])
            # rr, cc = line(yy[li], xx[li], yy[li+1], xx[li+1])
            rr_list.append(rr)
            cc_list.append(cc)

    # stack coordinates
    rr = np.hstack(rr_list)
    cc = np.hstack(cc_list)
    lbboxes = np.stack(lbbox_list)
    return rr, cc, lbboxes
示例#32
0
def draw_pose_from_cords(pose_joints, img_size, radius=2, draw_joints=True):
    colors = np.zeros(shape=img_size + (3, ), dtype=np.uint8)
    mask = np.zeros(shape=img_size, dtype=bool)

    if draw_joints:
        for f, t in LIMB_SEQ:
            from_missing = MISSING(pose_joints[f][0]) or MISSING(
                pose_joints[f][1])
            to_missing = MISSING(pose_joints[t][0]) or MISSING(
                pose_joints[t][1])
            if from_missing or to_missing:
                continue
            ''' 
            Trick, use a 4-polygon with 1 pixel width to represent lines, involve shape control.

            yy, xx = polygon(
                [pose_joints[f][0], pose_joints[t][0], pose_joints[t][0]+1, pose_joints[f][0]+1], 
                [pose_joints[f][1], pose_joints[t][1], pose_joints[t][1]+1, pose_joints[f][1]+1], 
                shape=img_size
            )
            '''
            yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1],
                                  pose_joints[t][0], pose_joints[t][1])
            valid_ids = [
                i for i in range(len(yy))
                if 0 < yy[i] < img_size[0] and 0 < xx[i] < img_size[1]
            ]
            yy, xx, val = yy[valid_ids], xx[valid_ids], val[valid_ids]
            colors[yy, xx] = np.expand_dims(val, 1) * 255
            mask[yy, xx] = True

    for i, joint in enumerate(pose_joints):
        if MISSING(pose_joints[i][0]) or MISSING(pose_joints[i][1]):
            continue
        yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size)
        colors[yy, xx] = COLORS[i]
        mask[yy, xx] = True

    return colors, mask
示例#33
0
def simplify_polygon(pol, tol=2, max_iter=20):
    """
        Inputs: Accepts a polygon, tolerance=2 and maximum iteration.
        Default values are tol=2 and max_iter=20
        Outputs: Simplified Polygon. Works kind of like measure.approximate_polygon.
        Example:
        >> POL = [
                                        [125, 270], [157, 307], [131, 323]
                        ]
        >> simplify_polygon(POL)
    """
    iiter = 0
    while True:
        iiter = iiter + 1
        pol1 = []
        can_skip = set()
        i = 1
        while i < len(pol) - 1:
            p0, p1 = pol[i - 1], pol[i + 1]
            rr, cc, val = draw.line_aa(int(p0[0]), int(p0[1]), int(p1[0]),
                                       int(p1[1]))
            pts = set(zip(rr, cc))
            pi = set()
            for x in range(int(int(pol[i][0]) - tol / 2),
                           int(int(pol[i][0]) + tol / 2) + 1):
                for y in range(int(int(pol[i][1]) - tol / 2),
                               int(int(pol[i][1]) + tol / 2) + 1):
                    pi.add((x, y))
            if len(pi.intersection(pts)) > 0:
                can_skip.add(i)
                i = i + 1
            i = i + 1
        if len(can_skip) == 0 or iiter >= max_iter:
            break
        for i in range(len(pol)):
            if i not in can_skip:
                pol1.append(pol[i])
        pol = pol1
    return pol
示例#34
0
    def draw_graph(self, data_vector, color):
        #interpolate the data vector to fill in gaps
        d_interpld = interp1d(self.state_x, data_vector)

        #convert data vector to a data array the size of the window's x dimension
        data_bar = np.array(
            [-d_interpld(x) * self.bhh + 0.5 for x in self.window_x],
            dtype=np.int)

        # All locations where we need to draw lines
        data_jump_locs = []

        for loc in np.where(abs(data_bar[:-1] - data_bar[1:]) >= 2)[0]:
            rr, cc, val = line_aa(data_bar[loc] + self.fh + self.bhh, loc,
                                  data_bar[loc + 1] + self.fh + self.bhh,
                                  loc + 1)
            data_jump_locs.append((rr, cc))
        """ Draw the speed and steering lines on the bar below the video. 
        Takes about 1ms to run through the for loops"""
        self.window[data_bar + self.fh + self.bhh, self.fwi, :] = color
        for rr, cc in data_jump_locs:
            self.window[rr, cc, :] = color
    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 = circle(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
示例#36
0
    def drawLine(self, centerX, centerY, angle, length, colour):
        """Plot a line from an angle, length and center
        Parameters:
            colour: 0:1 intensity percentage

        Attributes:

        """
        # Calculate the offset of the start and end from the center
        radAngle = math.radians(angle)
        xOffset = length * math.cos(radAngle)
        yOffset = length * math.sin(radAngle)

        # Calculate start and finish of the lines
        startx = math.floor(centerX - xOffset)
        stopx = math.floor(centerX + xOffset)
        starty = math.floor(centerY - yOffset)
        stopy = math.floor(centerY + yOffset)
        # Draw the line onto the array
        rr, cc, val = line_aa(starty, startx, stopy, stopx)
        #rr, cc = line(starty, startx, stopy, stopx)
        self._outputImage[rr, cc] = colour * 255
示例#37
0
def generate_canvas(rhos, thetas, frame):
    """
    From every line segment a line is extended in either direction. This is line is then drawn on canvas. 
    Based on the line density(i.e. number of intersections) we can identify a vanishing point
    :param rhos: 
    :param thetas: 
    :param frame: 
    :return: canvas
    """
    h, w, c = frame.shape
    canvas = np.zeros((h * 5, w * 5), np.int)
    for rho, theta in zip(rhos, thetas):
        a = np.cos(theta)
        b = np.sin(theta)
        rho = rho + (2. * h) * b + (2. * w) * a
        if b == 0:
            x1, x2 = rho / a, (rho - h * 5 * b) / a
            y1, y2 = rho, rho
        elif a == 0:
            y1, y2 = rho / b, (rho - w * 5 * a) / b
            x1, x2 = rho, rho
        else:
            x1, x2, y1, y2 = rho / a, (rho - h * 5 * b) / a, rho / b, (
                rho - w * 5 * a) / b

        coordinates = []
        if 0 <= x1 < w * 5:
            coordinates.append((int(x1), 0))
        if 0 <= x2 < w * 5:
            coordinates.append((int(x2), int(h * 5 - 1)))
        if 0 <= y1 < h * 5:
            coordinates.append((0, int(y1)))
        if 0 <= y2 < h * 5:
            coordinates.append((int(w * 5 - 1), (int(y2))))
        [(x1, y1), (x2, y2)] = coordinates
        rr, cc, val = line_aa(y1, x1, y2, x2)
        canvas[rr, cc] = canvas[rr, cc] + 1
    return canvas
示例#38
0
    def graph_image(self, xs, ys):
        """
        creates an image that represents the graph structure of connected nodes
        used for plotting as an image, so that the scale is the same as the occupancy images
        """

        img = np.zeros((len(xs), len(ys)))

        for n in self.nodes:
            x = n.data['location'][0]
            y = n.data['location'][1]

            # Index of the coordinate in the array
            # NOTE: this might be slightly incorrect....?
            ix = (np.abs(xs - x)).argmin()
            iy = (np.abs(ys - y)).argmin()

            img[ix, iy] = 1  #TEMP

            # Go through the neighbor indices of each neighbor
            for ni in n.get_neighbors():
                # Draw a line between the current node and the neighbor node
                nx = self.nodes[ni].data['location'][0]
                ny = self.nodes[ni].data['location'][1]

                inx = (np.abs(xs - nx)).argmin()
                iny = (np.abs(ys - ny)).argmin()

                # rr, cc = line(ix, iy, inx, iny)

                # anti-aliased line
                rr, cc, val = line_aa(ix, iy, inx, iny)

                img[rr, cc] = val

        # print(np.max(img))

        return img
示例#39
0
def line(img, coord, color):
    """
    Draws a line on the input image
    
    Parameters
    ----------
    img:        numpy.ndarray
                input image with shape [nb_lin, nb_col, nb_channels]
                
    coord:      tuple of integers with format (y1, x1, y2, x2)
                position (before rotation) and size of the rectangle 
                
    color:      array like type
                Rectangle color.  Size of array must be equal to nb_channels of 
                input img

    Returns
    -------
    out         numpy.ndarray
                img with drawn rectangle
    """

    # Line coordinates
    y1, x1, y2, x2 = coord

    # Generate line coordinates
    rr, cc, val = line_aa(y1, x1, y2, x2)

    # Draw line color
    out = img.copy()
    val = val[:, None]
    color = np.asarray(color)[None, :]
    print "(out[rr, cc] * (1 - val)).shape = ", (out[rr, cc] * (1 - val)).shape
    print "(out[rr, cc] * val * color).shape = ", (out[rr, cc] * val *
                                                   color).shape
    out[rr, cc] = out[rr, cc] * (1 - val) + out[rr, cc] * val * color

    return out
示例#40
0
    def line(self,
             row1: int,
             col1: int,
             row2: int,
             col2: int,
             color: ColorType = None,
             alpha: float = 1.0) -> 'Layer':
        """
        Draw a line between two points

        :param row1: Start row
        :param col1: Start column
        :param row2: End row
        :param col2: End column
        :param color: Color to draw with
        """
        rr, cc, aa = draw.line_aa(clamp(0, self.height, row1),
                                  clamp(0, self.width, col1),
                                  clamp(0, self.height, row2),
                                  clamp(0, self.width, col2))
        self._draw(rr, cc, color, aa)

        return self
def hog(image, orientations=9, pixels_per_cell=(8, 8),
        cells_per_block=(2, 2), visualise=True, normalise=False):
    """Extract Histogram of Oriented Gradients (HOG) for a given image.

    Compute a Histogram of Oriented Gradients (HOG) by

        1. (optional) global image normalisation
        2. computing the gradient image in x and y
        3. computing gradient histograms
        4. normalising across blocks
        5. flattening into a feature vector

    Parameters
    ----------
    image : (M, N) ndarray
        Input image (greyscale).
    orientations : int
        Number of orientation bins.
    pixels_per_cell : 2 tuple (int, int)
        Size (in pixels) of a cell.
    cells_per_block  : 2 tuple (int,int)
        Number of cells in each block.
    visualise : bool, optional
        Also return an image of the HOG.
    normalise : bool, optional
        Apply power law compression to normalise the image before
        processing.

    Returns
    -------
    newarr : ndarray
        HOG for the image as a 1D (flattened) array.
    hog_image : ndarray (if visualise=True)
        A visualisation of the HOG image.

    References
    ----------
    * http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients

    * Dalal, N and Triggs, B, Histograms of Oriented Gradients for
      Human Detection, IEEE Computer Society Conference on Computer
      Vision and Pattern Recognition 2005 San Diego, CA, USA

    """
    image = np.atleast_2d(image)

    """
    The first stage applies an optional global image normalisation
    equalisation that is designed to reduce the influence of illumination
    effects. In practice we use gamma (power law) compression, either
    computing the square root or the log of each colour channel.
    Image texture strength is typically proportional to the local surface
    illumination so this compression helps to reduce the effects of local
    shadowing and illumination variations.
    """

    if image.ndim > 3:
        raise ValueError("Currently only supports grey-level images")

    if normalise:
        image = sqrt(image)

    """
    The second stage computes first order image gradients. These capture
    contour, silhouette and some texture information, while providing
    further resistance to illumination variations. The locally dominant
    colour channel is used, which provides colour invariance to a large
    extent. Variant methods may also include second order image derivatives,
    which act as primitive bar detectors - a useful feature for capturing,
    e.g. bar like structures in bicycles and limbs in humans.
    """

    gx = np.zeros(image.shape)
    gy = np.zeros(image.shape)
    gx[:, :-1] = np.diff(image, n=1, axis=1)
    gy[:-1, :] = np.diff(image, n=1, axis=0)

    """
    The third stage aims to produce an encoding that is sensitive to
    local image content while remaining resistant to small changes in
    pose or appearance. The adopted method pools gradient orientation
    information locally in the same way as the SIFT [Lowe 2004]
    feature. The image window is divided into small spatial regions,
    called "cells". For each cell we accumulate a local 1-D histogram
    of gradient or edge orientations over all the pixels in the
    cell. This combined cell-level 1-D histogram forms the basic
    "orientation histogram" representation. Each orientation histogram
    divides the gradient angle range into a fixed number of
    predetermined bins. The gradient magnitudes of the pixels in the
    cell are used to vote into the orientation histogram.
    """

    magnitude = sqrt(gx ** 2 + gy ** 2)
    orientation = arctan2(gy, (gx + 1e-15)) * (180 / pi) + 90

    sy, sx = image.shape
    cx, cy = pixels_per_cell
    bx, by = cells_per_block

    n_cellsx = int(np.floor(sx // cx))  # number of cells in x
    n_cellsy = int(np.floor(sy // cy))  # number of cells in y

    # compute orientations integral images
    orientation_histogram = np.zeros((n_cellsy, n_cellsx, orientations))
    for i in range(orientations):
        #create new integral image for this orientation
        # isolate orientations in this range

        temp_ori = np.where(orientation < 180 / orientations * (i + 1),
                            orientation, 0)
        temp_ori = np.where(orientation >= 180 / orientations * i,
                            temp_ori, 0)
        # select magnitudes for those orientations
        cond2 = temp_ori > 0
        temp_mag = np.where(cond2, magnitude, 0)

        orientation_histogram[:,:,i] = uniform_filter(temp_mag, size=(cy, cx))[cy/2::cy, cx/2::cx]


    # now for each cell, compute the histogram
    #orientation_histogram = np.zeros((n_cellsx, n_cellsy, orientations))

    radius = min(cx, cy) // 2 - 1
    hog_image = None
    if visualise:
        hog_image = np.zeros((sy, sx), dtype=float)

    if visualise:
        from skimage import draw

        for x in range(n_cellsx):
            for y in range(n_cellsy):
                for o in range(orientations):
                    centre = tuple([y * cy + cy // 2, x * cx + cx // 2])
                    dx = radius * cos(float(o) / orientations * np.pi)
                    dy = radius * sin(float(o) / orientations * np.pi)

                    rr, cc, val = draw.line_aa(centre[0] - int(dx), centre[1] - int(dy), centre[0] + int(dx), centre[1] + int(dy))
                    hog_image[rr, cc] += orientation_histogram[y, x, o]

    """
    The fourth stage computes normalisation, which takes local groups of
    cells and contrast normalises their overall responses before passing
    to next stage. Normalisation introduces better invariance to illumination,
    shadowing, and edge contrast. It is performed by accumulating a measure
    of local histogram "energy" over local groups of cells that we call
    "blocks". The result is used to normalise each cell in the block.
    Typically each individual cell is shared between several blocks, but
    its normalisations are block dependent and thus different. The cell
    thus appears several times in the final output vector with different
    normalisations. This may seem redundant but it improves the performance.
    We refer to the normalised block descriptors as Histogram of Oriented
    Gradient (HOG) descriptors.
    """

    n_blocksx = (n_cellsx - bx) + 1
    n_blocksy = (n_cellsy - by) + 1
    normalised_blocks = np.zeros((n_blocksy, n_blocksx,
                                  by, bx, orientations))

    for x in range(n_blocksx):
        for y in range(n_blocksy):
            block = orientation_histogram[y:y + by, x:x + bx, :]
            eps = 1e-5
            normalised_blocks[y, x, :] = block / sqrt(block.sum() ** 2 + eps)

    """
    The final step collects the HOG descriptors from all blocks of a dense
    overlapping grid of blocks covering the detection window into a combined
    feature vector for use in the window classifier.
    """

    if visualise:
        return normalised_blocks.ravel(), hog_image
    else:
        return normalised_blocks.ravel()
示例#42
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()
示例#43
0
def fast_triangle_mesh_drawer(tris, origin, look):
  # shouldn't do anything
  look /= norm(look)

  img = np.zeros((Y, X))
  zimg = np.ones((Y, X))*np.inf

  def project_point(pt):
    # vector from pt to origin
    vv = pt - origin
    v = vv/norm(vv)

    # real projection shit
    vx = npa((v[0], 0, v[2]))
    lx = npa((look[0], 0, look[2]))
    vy = npa((0, v[1], v[2]))
    ly = npa((0, look[1], look[2]))
    def ang(v1, v2):
      v1 /= norm(v1)
      v2 /= norm(v2)
      angl = np.dot(v1, v2)
      crs = np.cross(v1, v2)
      if np.sum(crs) >= 0.0:
        return np.arccos(angl)
      else:
        return -np.arccos(angl)

    x = (ang(vx, lx) / arcrad_per_pixel)
    y = (ang(vy, ly) / arcrad_per_pixel)

    # add z for z-buffering
    # z is the distance of the point from the plane formed by look and origin

    # project v on to look
    z = np.dot(v, look) * norm(vv)

    """
    print " *** "
    print v, K
    print pt, x, y
    """

    return int(round(x + X/2)),int(round(Y/2 - y)), z

  # project the triangles into 2D space
  # does this projection preserve the u and v
  DRAW_WIREFRAME = False
  if DRAW_WIREFRAME:
    lines = []
    for tr in tris:
      p0, p1, p2 = project_point(tr[0]), project_point(tr[1]), project_point(tr[2])
      lines.append((p0[0:2], p1[0:2]))
      lines.append((p1[0:2], p2[0:2]))
      lines.append((p2[0:2], p0[0:2]))

    for pt1, pt2 in lines:
      rr, cc, val = line_aa(pt1[1], pt1[0], pt2[1], pt2[0])

      # filter
      rr[np.logical_or(rr < 0, rr >= Y)] = 0
      cc[np.logical_or(cc < 0, cc >= X)] = 0

      img[rr, cc] = val
  else:
    # z-buffering, keeping the quality low in line with the rest of the program
    polys = []
    for tr in tris:
      xyz = npa(map(project_point, tr))

      # get min and max
      xmin, xmax = np.min(xyz[:, 0]), np.max(xyz[:, 0])
      ymin, ymax = np.min(xyz[:, 1]), np.max(xyz[:, 1])

      # on screen
      xmin = np.clip(xmin, 0, X).astype(np.int)
      xmax = np.clip(xmax, 0, X).astype(np.int)
      ymin = np.clip(ymin, 0, Y).astype(np.int)
      ymax = np.clip(ymax, 0, Y).astype(np.int)

      # triangle in 3 space
      vs1 = xyz[1][0:2] - xyz[0][0:2]
      vs2 = xyz[2][0:2] - xyz[0][0:2]
      vsx = np.cross(vs1, vs2)

      # shade
      shade = random.uniform(0.3, 1.0)

      for x in range(xmin, xmax):
        for y in range(ymin, ymax):
          q = npa([x,y]) - xyz[0][0:2]
          u = np.cross(q, vs2) / vsx
          v = np.cross(vs1, q) / vsx
          if u >= 0 and v >= 0 and u+v <= 1.0:
            pt_xyz = (1-u-v)*xyz[0] + u*xyz[1] + v*xyz[2]
            if pt_xyz[2] < zimg[y,x]:
              zimg[y,x] = pt_xyz[2]
              img[y,x] = shade
      #polys.append((np.mean(xyz[:, 2]), xyz))
     
    """
    polys = sorted(polys, reverse=True, key=lambda x: x[0])
    for _, xyz in polys:
      rr, cc = polygon(xyz[:, 1], xyz[:, 0])

      rr[np.logical_or(rr < 0, rr >= Y)] = 0
      cc[np.logical_or(cc < 0, cc >= X)] = 0
      img[rr, cc] = random.uniform(0.3, 1.0)
    """
  return img
示例#44
0
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt

from skimage.transform import hough_line, hough_line_peaks
from skimage.draw import line_aa


if __name__ == '__main__':
    # Construct test image
    image = np.zeros((200, 100))

    # Line 0
    rr, cc, val = line_aa(50, 15, 140, 97)
    image[rr, cc] = val

    # Line 1
    rr, cc, val = line_aa(100, 5, 12, 84)
    image[rr, cc] = np.fmax(image[rr, cc], val)

    # Line 2
    rr, cc, val = line_aa(140, 15, 160, 80)
    image[rr, cc] = np.fmax(image[rr, cc], val)

    # Compute the Hough transform for display
    h, theta, d = hough_line(image)

    fig, ax = plt.subplots(1, 3, figsize=(6, 3.5))

    # Original image
    ax[0].imshow(image, cmap=plt.cm.gray)
示例#45
0
文件: util.py 项目: sssruhan1/spine
def add_line(arr, p1x, p1y, p2x, p2y):
    from skimage.draw import line_aa
    rr, cc, val = line_aa(p1y, p1x, p2y, p2x)
    arr[rr, cc] = val * 255
    
    return arr