Ejemplo n.º 1
0
def display_bounding_boxes_within_notebook(page_num,
                                           extractor,
                                           blocks,
                                           alternatecolors=False,
                                           color=Color("blue")):
    """
    Displays each of the bounding boxes passed in 'boxes' on an image of the pdf
    pointed to by pdf_file
    boxes is a list of 5-tuples (page, top, left, bottom, right)
    """
    elems = extractor.elems[page_num]
    page_width, page_height = int(elems.layout.width), int(elems.layout.height)
    img = pdf_to_img(extractor.pdf_file, page_num, page_width, page_height)
    draw = Drawing()
    draw.fill_color = Color("rgba(0, 0, 0, 0)")
    draw.stroke_color = color
    for block in blocks:
        top, left, bottom, right = block[-4:]
        if alternatecolors:
            draw.stroke_color = Color("rgba({},{},{}, 1)".format(
                str(np.random.randint(255)),
                str(np.random.randint(255)),
                str(np.random.randint(255)),
            ))
        draw.rectangle(left=float(left),
                       top=float(top),
                       right=float(right),
                       bottom=float(bottom))
        draw(img)
    return img
def makeCluster(dimensions, path_list, city_list):
	with Drawing() as draw:
		with Image(width=dimensions[1], height=dimensions[0], background=None) as image:
			all_lines = []
			for path in path_list:
				current_city = 0
				next_city = 1
				while next_city < len(path):
					line_dimensions = ((city_list[path[current_city]],city_list[path[next_city]]))
					all_lines.append(line_dimensions)
					current_city += 1
					next_city += 1
				all_lines.append((city_list[path[0]],city_list[path[-1]]))
			for a_line in all_lines:
				draw.line(a_line[0], a_line[1])
				draw(image)

			draw.stroke_color = Color('black')
			draw.stroke_width = 2
			draw.fill_color = Color('white')
			for city in city_list:
				draw.circle(city,(city[0]+10,city[1]+10))
				draw.stroke_color = Color('black')
				draw.stroke_width = 2
				draw.fill_color = Color('white')
				draw(image)

			image.save(filename = 'cluster.png')
Ejemplo n.º 3
0
 def display_boxes(self, pdf_file, boxes, alternate_colors=False):
     """
     Displays each of the bounding boxes passed in 'boxes' on images of the pdf
     pointed to by pdf_file
     boxes is a list of 5-tuples (page, top, left, bottom, right)
     """
     imgs = []
     colors = [Color("blue"), Color("red")]
     boxes_per_page = defaultdict(int)
     boxes_by_page = defaultdict(list)
     for i, (page, top, left, bottom, right) in enumerate(boxes):
         boxes_per_page[page] += 1
         boxes_by_page[page].append((top, left, bottom, right))
     for i, page_num in enumerate(boxes_per_page.keys()):
         img = pdf_to_img(pdf_file, page_num)
         draw = Drawing()
         draw.fill_color = Color("rgba(0, 0, 0, 0.0)")
         for j, (top, left, bottom,
                 right) in enumerate(boxes_by_page[page_num]):
             draw.stroke_color = colors[
                 j % 2] if alternate_colors else colors[0]
             draw.rectangle(left=left, top=top, right=right, bottom=bottom)
         draw(img)
         imgs.append(img)
     return imgs
Ejemplo n.º 4
0
def test_clone_drawing_wand(fx_wand):
    fx_wand.text_kerning = 10.22
    funcs = (lambda img: Drawing(drawing=fx_wand), lambda img: fx_wand.clone())
    for func in funcs:
        with func(fx_wand) as cloned:
            assert fx_wand.resource is not cloned.resource
            assert fx_wand.text_kerning == cloned.text_kerning
def draw_address(addr, position):
    try:
        logger.debug('Address to draw: ' + addr)

        if position == 'top':
            left_coord = bill_features['addr_top'][0]
            top_coord = bill_features['addr_top'][1]
        elif position == 'middle':
            left_coord = bill_features['addr_middle'][0]
            top_coord = bill_features['addr_middle'][1]
        elif position == 'bottom':
            left_coord = bill_features['addr_bottom'][0]
            top_coord = bill_features['addr_bottom'][1]

        with Drawing() as draw:
            draw.font_family = 'Ubuntu'
            draw.font_size = bill_features['font_size']
            draw.text(left_coord, top_coord, addr)
            with Image(filename=bill_file) as img:
                img.rotate(90)
                draw.draw(img)
                img.rotate(270)
                img.save(filename=bill_file)

    except Exception as e:
        logger.exception(
            'Exception while drawing public address on bill overlay.')
        logger.exception(e)
        raise
def draw_label(position, text):
    logger.info('Adding label to bill overlay.')

    try:
        if position == 'top':
            x_label = bill_features['label_top'][0]
            y_label = bill_features['label_top'][1]
        elif position == 'middle':
            x_label = bill_features['label_middle'][0]
            y_label = bill_features['label_middle'][1]
        elif position == 'bottom':
            x_label = bill_features['label_bottom'][0]
            y_label = bill_features['label_bottom'][1]

        with Drawing() as draw:
            draw.font_family = 'Ubuntu'
            draw.font_style = 'oblique'
            draw.font_size = bill_features['font_size']
            draw.text_alignment = 'left'
            draw.text(x_label, y_label, text)
            with Image(filename=bill_file) as layout:
                draw.draw(layout)
                layout.save(filename=bill_file)

    except Exception as e:
        logger.exception('Exception while drawing label on bill overlay.')
        logger.exception(e)
        raise
Ejemplo n.º 7
0
def test_wand():
    import pathlib

    from wand.color import Color
    from wand.drawing import Drawing
    from wand.image import Image

    with Image(width=500, height=500) as outer:
        background_color = Color('#f00')
        with Image(width=250, height=250, background=background_color) as red_inner:
            outer.composite(red_inner, left=125, top=125)
        with outer.convert('png') as converted:
            converted.save(filename='_test_wand.png')

    assert pathlib.Path('_test_wand.png').exists()

    with Drawing() as draw:
        draw.stroke_color = Color('black')
        draw.stroke_width = 2
        draw.fill_color = Color('white')
        draw.arc(
            (25, 25),
            (75, 75),
            (135, -45)
        )

        with Image(width=100, height=100, background=Color('lightblue')) as im:
            draw.draw(im)
            with im.convert('png') as converted:
                converted.save(filename='_test_wand_2.png')

    assert pathlib.Path('_test_wand_2.png').exists()
Ejemplo n.º 8
0
 def test_affinetransform(self):
     f = wpi.affinetransform
     with self.rose.clone() as t:
         with Drawing() as d:
             d.affine([2.0, 0.0, 0.0, 2.0, 0.0, 0.0])
             f(t, d)  # not work correctly (IM<6.9.9-36)
             save(t, f)
Ejemplo n.º 9
0
def create_composite_sprite(sprites, out_fn, pix_height):
    with Drawing() as draw:
        draw.gravity = 'center'

        width = height = 128
        basis_y = 0
        if pix_height > 256:
            width = height = 512
            basis_y = 128 + 64
        elif pix_height > 128:
            width = height = 256
            basis_y = 64

        last_parent = None
        for i, sp in enumerate(sprites):
            ageStart, ageEnd = sp['ageRange']
            if not ageStart < 20 and (ageEnd > 20 or ageEnd == -1):
                next

            x, y = sp['pos']
            offset_x, offset_y = sp['offset']
            x -= offset_x
            y = -y - offset_y + basis_y
            r = (sp['rot'] * 360) % 360
            _draw_sprite(draw, sp['sprite'], x, y, r)

        with Image(width=width, height=height,
                   background=Color('transparent')) as img:
            draw.draw(img)
            img.save(filename=out_fn)
Ejemplo n.º 10
0
def saveFile():
    global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH
    draw = Drawing()  # 빈 판
    # 빈 판에 컬러 -> #000000 ~ #FFFFFF
    saveFp = asksaveasfile(parent=window,
                           mode='w',
                           defaultextension='.png',
                           filetypes=(("그림파일",
                                       "*.gif;*.jpg;*.png;*.tif;*.bmp"),
                                      ("모든파일", "*.*")))
    for i in range(outW):
        for j in range(outH):
            dataR = outImage[i][j][0]
            dataG = outImage[i][j][1]
            dataB = outImage[i][j][2]
            hexStr = '#'
            if dataR > 15:
                hexStr += hex(dataR)[2:]
            else:
                hexStr += ('0' + hex(dataR)[2:])
            if dataG > 15:
                hexStr += hex(dataG)[2:]
            else:
                hexStr += ('0' + hex(dataG)[2:])
            if dataB > 15:
                hexStr += hex(dataB)[2:]
            else:
                hexStr += ('0' + hex(dataB)[2:])
            draw.fill_color = Color(hexStr)
            draw.color(j, i, 'replace')
    with Image(filename=filename) as img:
        draw(img)
        img.save(filename=saveFp.name)
    print("SAVE OK")
Ejemplo n.º 11
0
def beziersample(pointlists, filename):
    w = 100
    h = 100
    bgcolor = Color('skyblue')

    with Image(width=w, height=h, background=bgcolor) as img:
        with Drawing() as draw:
            draw.stroke_width = 1
            draw.fill_color = Color('none')

            # draw control lines
            draw.stroke_color = Color('gray')
            for points in pointlists:
                for i in range(0, len(points), 2):
                    draw.line(points[i], points[i + 1])

            # draw points
            draw.stroke_color = Color('blue')
            for points in pointlists:
                for point in points:
                    drawcross(draw, point, 4)

            # draw bezier
            draw.stroke_color = Color('red')
            for points in pointlists:
                draw.bezier(points)

            draw(img)
            img.save(filename=filename)
Ejemplo n.º 12
0
def display_bounding_boxes(img,
                           blocks,
                           alternatecolors=False,
                           color=Color("blue")):
    """
    Displays each of the bounding boxes passed in 'boxes' on an image of the pdf
    pointed to by pdf_file
    boxes is a list of 5-tuples (page, top, left, bottom, right)
    """
    draw = Drawing()
    draw.fill_color = Color("rgba(0, 0, 0, 0)")
    draw.stroke_color = color
    for block in blocks:
        top, left, bottom, right = block[-4:]
        if alternatecolors:
            draw.stroke_color = Color("rgba({},{},{}, 1)".format(
                str(np.random.randint(255)),
                str(np.random.randint(255)),
                str(np.random.randint(255)),
            ))
        draw.rectangle(left=float(left),
                       top=float(top),
                       right=float(right),
                       bottom=float(bottom))
        draw(img)
    display(img)
Ejemplo n.º 13
0
def animate_slice(sliceviewer,
                  name,
                  start,
                  end,
                  filename,
                  num_frames=10,
                  font_size=24):
    """Generate an animated gif of a 2D slice moving through a third dimension.

    Args:
        sliceviewer (SliceViewer): A sliceviewer instance.
        name (str): The name of the third dimension to use.
        start (float): The starting value of the third dimension.
        end (float): The end value of the third dimension.
        filename (str): The file to save the gif to.

    Kwargs:
        num_frames (int): The number of frames the gif should contain.
        font_size: (int): The size of the caption.

    Example:
        ws = CreateMDWorkspace(3, Extents=[-10,10,-10,10,-10,10], Names=["X","Y","Z"], Units=["u","u","u"])
        FakeMDEventData(ws, PeakParams=[10000,0,0,0,1])
        sv = plotSlice(ws)
        #Resize and configure the slice viewer how you want the output to look
        sv.setNormalization(1) # We need to normalize by volume in this case, or the data won't show up
        #This will create a gif iterating from Z = -1 to Z = 1
        animate_slice(sv, "Z", -1, 1, "output.gif")
    """
    #Generate all the individual frames
    images = []
    for slice_point in numpy.linspace(start, end, num_frames):
        sliceviewer.setSlicePoint(name, slice_point)
        sliceviewer.refreshRebin()
        qimg = sliceviewer.getImage().toImage()
        data = QByteArray()
        buf = QBuffer(data)
        qimg.save(buf, "PNG")
        image = Image(blob=str(data))
        captionstrip_size = font_size + 10
        #To add whitespace to the top, we add a vertical border,
        #then crop out the bottom border
        image.border(Color("#fff"), 0, captionstrip_size)
        image.crop(0, 0, image.width, image.height - captionstrip_size)
        #Write the caption into the whitespace
        draw = Drawing()
        draw.font_size = font_size
        draw.text(5, font_size, "%s = %g" % (name, slice_point))
        draw(image)
        images.append(image)
    #Create a new image with the right dimensions
    animation = Image(width=images[0].width, height=images[0].height)
    #Copy in the frames from all the generated images
    for image in images:
        animation.sequence.append(image.sequence[0])
    #Drop the initial blank frame
    del animation.sequence[0]
    #Write the animation to disk
    animation.save(filename=filename)
Ejemplo n.º 14
0
def draw_canvas():
    with Drawing() as draw:
        draw.fill_color = Color('transparent')
        #draw.fill_color = Color('white')
        draw.rectangle(left=0, top=0, width=bill_features['canvas'][0], height=bill_features['canvas'][1])
        with Image(width=bill_features['canvas'][0], height=bill_features['canvas'][1]) as img:
            draw.draw(img)
            img.save(filename=bill_file)
Ejemplo n.º 15
0
 def test_imagesize(self):
     with Drawing() as d:
         text = 'check'
         d.font = 'Arial'
         d.font_size = 36
         size = calcSuitableImagesize(d, text)
         print('calcSuitableImagesize: ', size)
         self.assertTrue(size[0] > 0 and size[1] > 0)
Ejemplo n.º 16
0
def test_draw_comment():
    comment = 'pikachu\'s ghost'
    expected = '#pikachu\'s ghost\n'
    with nested(Image(width=1, height=1), Drawing()) as (img, draw):
        draw.comment(comment)
        draw(img)
        blob = img.make_blob(format="mvg")
        assert expected == text(blob)
Ejemplo n.º 17
0
 def draw_rectangle(self, x, y, width, height):  # pragma: no cover
     """draw_rectangle is used only in `/debug` routes"""
     with Drawing() as draw:
         draw.fill_color = "transparent"
         draw.stroke_color = "white"
         draw.stroke_width = 1
         draw.rectangle(x, y, width=width, height=height)
         draw(self.image)
Ejemplo n.º 18
0
def test_draw_push_pop():
    with Drawing() as draw:
        draw.stroke_width = 2
        draw.push()
        draw.stroke_width = 3
        assert 3 == draw.stroke_width
        draw.pop()
        assert 2 == draw.stroke_width
Ejemplo n.º 19
0
def test_draw_matte_user_error():
    with Drawing() as draw:
        with raises(TypeError):
            draw.matte()
        with raises(TypeError):
            draw.matte(1, 2, 4)
        with raises(ValueError):
            draw.matte(1, 2, 'apples')
Ejemplo n.º 20
0
def test_draw_point():
    with nested(Color('#fff'), Color('#000')) as (white, black):
        with Image(width=5, height=5, background=white) as img:
            with Drawing() as draw:
                draw.stroke_color = black
                draw.point(2, 2)
                draw.draw(img)
                assert img[2, 2] == black
Ejemplo n.º 21
0
def test_draw_color_user_error():
    with Drawing() as draw:
        with raises(TypeError):
            draw.color()
        with raises(TypeError):
            draw.color(1, 2, 4)
        with raises(ValueError):
            draw.color(1, 2, 'apples')
Ejemplo n.º 22
0
def test_draw_matte():
    with nested(Color('#fff'), Color('transparent')) as (white, transparent):
        with Image(width=50, height=50, background=white) as img:
            with Drawing() as draw:
                draw.fill_opacity = 0
                draw.matte(25, 25, 'floodfill')
                draw.draw(img)
                assert img[25, 25] == transparent
Ejemplo n.º 23
0
def test_draw_color():
    with nested(Color('#fff'), Color('#000')) as (white, black):
        with Image(width=50, height=50, background=white) as img:
            with Drawing() as draw:
                draw.fill_color = black
                draw.color(25, 25, 'floodfill')
                draw.draw(img)
                assert img[25, 25] == black
Ejemplo n.º 24
0
def test_draw_alpha_user_error():
    with Drawing() as draw:
        with raises(TypeError):
            draw.alpha()
        with raises(TypeError):
            draw.alpha(1, 2, 4)
        with raises(ValueError):
            draw.alpha(1, 2, 'apples')
Ejemplo n.º 25
0
def test_draw_alpha():
    transparent = Color('transparent')
    with Image(width=50, height=50, pseudo='xc:white') as img:
        with Drawing() as draw:
            draw.fill_color = transparent
            draw.alpha(25, 25, 'floodfill')
            draw.draw(img)
        assert img[25, 25] == transparent
Ejemplo n.º 26
0
def render_text(
    img,
    text,
    font,
    *,
    antialias=True,
    padding=0,
    color="black",
    font_size_hint=12
):
    """ renders a text as large as possible on a provided image

    :param wand.image.Image img: a wand.image.Image instance
    :param str text: the text to render
    :param str font: path to a font file to use

    optional:
    :param bool antialias: use antialiasing, defaults to True
    :param int padding: padding to apply to the image for the text rendering
    :param str color: text color to use
    :param int font_size_hint: font
        size used as a starting point for the search of the largest font size,
        also used for finding the best way to wrap a text.
    :returns RenderingFit: parameters used to render the text on the image
    """

    box_size = Size(img.width - 2 * padding, img.height - 2 * padding)

    with Drawing() as sketch:
        # Set the basic font style
        sketch.fill_color = Color(color)
        sketch.font = font
        sketch.font_size = font_size_hint
        sketch.text_antialias = antialias

        # search for the largest font size to render the text inside the box
        best_fit = find_best_text_fit(sketch, img, box_size, text)
        sketch.font_size = best_fit.font_size

        # calculate the positioning of the text in the image
        # the y value used in sketch.text() method to render the text
        # specifies the baseline of the first line of text
        # this must be adjusted with the character height of the text
        x = (box_size.width - best_fit.width) // 2
        unadjusted_y = (box_size.height - best_fit.height) // 2
        y = unadjusted_y + best_fit.character_height

        # render the text and  return the image
        sketch.text(x, int(y), "\n".join(best_fit.lines))
        sketch.draw(img)

        return RenderingFit(
            lines=best_fit.lines,
            font_size=best_fit.font_size,
            x=int(x),
            y=int(y),
            character_height=best_fit.character_height,
        )
Ejemplo n.º 27
0
def test_draw_translate():
    with nested(Color('#fff'), Color('#000')) as (white, black):
        with Image(width=50, height=50, background=white) as img:
            with Drawing() as draw:
                draw.stroke_color = black
                draw.translate(x=5, y=5)
                draw.line((3, 3), (35, 35))
                draw.draw(img)
                assert img[40, 40] == black
Ejemplo n.º 28
0
def test_draw_skew():
    with nested(Color('#fff'), Color('#000')) as (white, black):
        with Image(width=50, height=50, background=white) as img:
            with Drawing() as draw:
                draw.stroke_color = black
                draw.skew(x=11, y=-24)
                draw.line((3, 3), (35, 35))
                draw.draw(img)
                assert img[43, 42] == black
Ejemplo n.º 29
0
def test_draw_path_line_user_error():
    with Drawing() as draw:
        # Test missing value
        with raises(TypeError):
            draw.path_line()
        with raises(TypeError):
            draw.path_horizontal_line()
        with raises(TypeError):
            draw.path_vertical_line()
Ejemplo n.º 30
0
def test_draw_point():
    white = Color('WHITE')
    black = Color('BLACK')
    with Image(width=5, height=5, background=white) as img:
        with Drawing() as draw:
            draw.stroke_color = black
            draw.point(2, 2)
            draw.draw(img)
            assert img[2, 2] == black