Example #1
0
def test_yellow_quantum():
    q = 2 ** QUANTUM_DEPTH - 1
    assert Color('cmyk(0, 0, 100%, 0)').yellow_quantum == q
    assert Color('cmyk(0, 0, 0, 0)').yellow_quantum == 0
    c = Color('none')
    c.yellow_quantum = q
    assert c.yellow_quantum == q
Example #2
0
def test_black_quantum():
    q = 2 ** QUANTUM_DEPTH - 1
    assert Color('cmyk(0, 0, 0, 100%)').black_quantum == q
    assert Color('cmyk(0, 0, 0, 0)').black_quantum == 0
    c = Color('none')
    c.black_quantum = q
    assert c.black_quantum == q
Example #3
0
def test_magenta_quantum():
    q = 2 ** QUANTUM_DEPTH - 1
    assert Color('cmyk(0, 100%, 0, 0)').magenta_quantum == q
    assert Color('cmyk(0, 0, 0, 0)').magenta_quantum == 0
    c = Color('none')
    c.magenta_quantum = q
    assert c.magenta_quantum == q
Example #4
0
def test_cyan_quantum():
    q = 2 ** QUANTUM_DEPTH - 1
    assert Color('cmyk(100%, 0, 0, 0)').cyan_quantum == q
    assert Color('cmyk(0, 0, 0, 0)').cyan_quantum == 0
    c = Color('none')
    c.cyan_quantum = q
    assert c.cyan_quantum == q
Example #5
0
def test_alpha():
    assert Color('rgba(0, 0, 0, 1)').alpha == 1
    assert Color('rgba(0, 0, 0, 0)').alpha == 0
    assert 0.49 <= Color('rgba(0, 0, 0, 0.5)').alpha <= 0.51
    c = Color('none')
    c.alpha = 1
    assert c.alpha == 1
Example #6
0
def test_green_int8():
    assert Color('black').green_int8 == 0
    assert Color('#0f0').green_int8 == 255
    assert Color('white').green_int8 == 255
    assert Color('rgba(0, 128, 0, 1)').green_int8 == 128
    c = Color('none')
    c.green_int8 = 255
    assert c.green_int8 == 255
Example #7
0
def test_red_int8():
    assert Color('black').red_int8 == 0
    assert Color('red').red_int8 == 255
    assert Color('white').red_int8 == 255
    assert Color('rgba(128, 0, 0, 1)').red_int8 == 128
    c = Color('none')
    c.red_int8 = 255
    assert c.red_int8 == 255
Example #8
0
def test_alpha_quantum():
    q = 2 ** QUANTUM_DEPTH - 1
    assert Color('rgba(0, 0, 0, 1)').alpha_quantum == q
    assert Color('rgba(0, 0, 0, 0)').alpha_quantum == 0
    assert (0.49 * q) < Color('rgba(0, 0, 0, 0.5)').alpha_quantum < (0.51 * q)
    c = Color('none')
    c.alpha_quantum = q
    assert c.alpha_quantum == q
Example #9
0
def test_blue_int8():
    assert Color('black').blue_int8 == 0
    assert Color('blue').blue_int8 == 255
    assert Color('white').blue_int8 == 255
    assert Color('rgba(0, 0, 128, 1)').blue_int8 == 128
    c = Color('none')
    c.blue_int8 = 255
    assert c.blue_int8 == 255
Example #10
0
def test_blue():
    assert Color('black').blue == 0
    assert Color('blue').blue == 1
    assert Color('white').blue == 1
    assert 0.5 <= Color('rgba(0, 0, 128, 1)').blue < 0.51
    c = Color('none')
    c.blue = 1
    assert c.blue == 1
Example #11
0
def test_red():
    assert Color('black').red == 0
    assert Color('red').red == 1
    assert Color('white').red == 1
    assert 0.5 <= Color('rgba(128, 0, 0, 1)').red < 0.51
    c = Color('none')
    c.red = 1
    assert c.red == 1
Example #12
0
def test_green():
    assert Color('black').green == 0
    assert Color('#0f0').green == 1
    assert Color('white').green == 1
    assert 0.5 <= Color('rgba(0, 128, 0, 1)').green < 0.51
    c = Color('none')
    c.green = 1
    assert c.green == 1
Example #13
0
def test_blue_quantum():
    q = 2 ** QUANTUM_DEPTH - 1
    assert Color('black').blue_quantum == 0
    assert Color('blue').blue_quantum == q
    assert Color('white').blue_quantum == q
    assert (0.49 * q) < Color('rgba(0, 0, 128, 1)').blue_quantum < (0.51 * q)
    c = Color('none')
    c.blue_quantum = q
    assert c.blue_quantum == q
Example #14
0
def test_alpha_int8():
    assert Color('rgba(0, 0, 0, 1)').alpha_int8 == 255
    assert Color('rgba(0, 0, 0, 0)').alpha_int8 == 0
    if not (Color('rgb(127,0,0)').red_quantum <=
            Color('rgba(0,0,0,0.5').alpha_quantum <=
            Color('rgb(128,0,0)').red_quantum):
        # FIXME: I don't know why, but the value PixelGetAlphaQuantum() returns
        #        is inconsistent to other PixelGet{Red,Green,Blue}Quantum()
        #        functions in Travis CI.  We just skip the test in this case.
        return
    assert 127 <= Color('rgba(0, 0, 0, 0.5)').alpha_int8 <= 128
    c = Color('none')
    c.alpha_int8 = 255
    assert c.alpha_int8 == 255
Example #15
0
def test_green_int8():
    assert Color('black').green_int8 == 0
    assert Color('#0f0').green_int8 == 255
    assert Color('white').green_int8 == 255
    assert Color('rgba(0, 128, 0, 1)').green_int8 == 128
Example #16
0
	print(img.height)
	img.resize(100, 56)
	img.save(filename = "sf_1.jpeg")


with Image(filename = 'sf.jpeg') as img:
	with img.clone() as flipped:
		flipped.flop()
		flipped.save(filename = 'sf-2.jpeg')

'''
#font = Font(path='./font/Americana Bold BT.ttf', size=64)
with Drawing() as draw:
    with Image(filename='sf.jpeg') as img:
        img.resize(300, 300)
        with Color('ivory') as color:
            draw.fill_color = color
            draw.rectangle(left=0, top=200, width=300, height=200)
        draw(img)
        img.save(filename='sf.jpeg')

with Drawing() as draw:
    with Image(filename='sf.jpeg') as img:
        with Color('black') as color:
            draw.font = './font/Americana Bold BT.ttf'
            draw.font_size = 15
            words = 'Golden Bridge is most famous view and symbols in SF'
            height = int(img.width - 100 + draw.font_size)
            length = int(img.width / draw.font_size * 1.5)
            if len(words) > length:
                draw.text(1, height, words[0:length])
Example #17
0
from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color
from wandplus.image import blur

# http://www.imagemagick.org/Usage/fonts/
# original imagemagick command:
# convert -size 320x100 xc:lightblue -font Candice -pointsize 72 \
#         -stroke black -strokewidth 8 -annotate +25+65 'Anthony' -blur 0x8 \
#         -fill white   -stroke none   -annotate +25+65 'Anthony' \
#         font_denser_soft_outline.jpg

w = 320
h = 100
with Image(width=w, height=h, background=Color('lightblue')) as img:
    with Drawing() as draw0:
        text = 'Anthony'
        draw0.font = 'Candice'
        draw0.font_size = 72
        draw0.gravity = 'forget'

        x = 25
        y = 65

        # drawing shadow
        with draw0.clone() as draw:
            draw.fill_color = Color('black')
            draw.stroke_color = Color('black')
            draw.stroke_width = 8
            draw.text(x, y, text)
Example #18
0
def test_alpha():
    assert Color('rgba(0, 0, 0, 1)').alpha == 1
    assert Color('rgba(0, 0, 0, 0)').alpha == 0
    assert 0.49 <= Color('rgba(0, 0, 0, 0.5)').alpha <= 0.5
Example #19
0
def test_cyan_int8():
    assert Color('cmyk(100%, 0, 0, 0)').cyan_int8 == 255
    assert Color('cmyk(0, 0, 0, 0)').cyan_int8 == 0
    c = Color('none')
    c.cyan_int8 = 255
    assert c.cyan_int8 == 255
Example #20
0
def test_not_equals():
    """Equality test."""
    assert Color('#000') != Color('#fff')
    assert Color('rgba(0, 0, 0, 0)') != Color('rgba(0, 0, 0, 1)')
    assert Color('rgba(0, 0, 0, 1)') != Color('rgba(1, 1, 1, 1)')
Example #21
0
def test_green():
    assert Color('black').green == 0
    assert Color('#0f0').green == 1
    assert Color('white').green == 1
    assert 0.5 <= Color('rgba(0, 128, 0, 1)').green < 0.51
Example #22
0
        draw.ellipse((50, 30), (40, 20))
        draw.fill_color = Color('blue')
        draw.circle((50, 30), (40, 20))
        draw.stroke_width = 5
        draw.stroke_color = Color('black')
        draw.fill_color = Color('none')
        draw.line((0, 30), (100, 30))
        draw.stroke_color = Color('royalblue')
        draw.line((50, 0), (50, 60))
        draw(img)
    return img


with color_test() as img:
    with Drawing() as draw:
        draw.fill_color = Color('white')
        draw.color(30, 20, 'replace')
        draw(img)
        img.save(filename='sample10a.png')

with color_test() as img:
    # Image.fuzz is not implemented yet. So use setfuzz in wandplus
    setfuzz(img, 0.13 * img.quantum_range)  # =13%
    with Drawing() as draw:
        draw.fill_color = Color('white')
        draw.color(30, 20, 'replace')
        draw(img)
        img.save(filename='sample10b.png')

with color_test() as img:
    with Drawing() as draw:
Example #23
0
def color_memory_leak():
    for i in xrange(5000):
        with Color('orange'):
            pass
    time.sleep(0.02)
Example #24
0
def test_magenta_int8():
    assert Color('cmyk(0, 100%, 0, 0)').magenta_int8 == 255
    assert Color('cmyk(0, 0, 0, 0)').magenta_int8 == 0
    c = Color('none')
    c.magenta_int8 = 255
    assert c.magenta_int8 == 255
Example #25
0
def test_yellow_int8():
    assert Color('cmyk(0, 0, 100%, 0)').yellow_int8 == 255
    assert Color('cmyk(0, 0, 0, 0)').yellow_int8 == 0
    c = Color('none')
    c.yellow_int8 = 255
    assert c.yellow_int8 == 255
Example #26
0
def test_hsl():
    with Color.from_hsl(hue=0.0, saturation=1.0, lightness=0.5) as c:
        assert c == Color('#f00')
    with Color('#00f') as c:
        assert c.hsl() == (0.6666666666666666, 1.0, 0.5)
Example #27
0
def test_fuzz():
    c = Color('none')
    c.fuzz = 55.5
    assert c.fuzz == 55.5
Example #28
0
def test_black_int8():
    assert Color('cmyk(0, 0, 0, 100%)').black_int8 == 255
    assert Color('cmyk(0, 0, 0, 0)').black_int8 == 0
    c = Color('none')
    c.black_int8 = 255
    assert c.black_int8 == 255
Example #29
0
def compose_adaptive_prey(img_paths=None,
                          match_json=None,
                          gap=5,
                          horizontal_gap=5,
                          description=None,
                          caption="Catcierge"):

    img = Image(width=600, height=1124, background=Color("#8A968E"))

    print("Font path: %s" % font_path)

    font = Font(path="%s/source-code-pro/SourceCodePro-Medium.otf" % font_path,
                size=64)
    font_title = Font(path="%s/alex-brush/AlexBrush-Regular.ttf" % font_path,
                      size=64)
    font_math = Font(path="%s/Asana-Math/Asana-Math.otf" % font_path, size=64)

    imgs = []
    assert (img_paths and (len(img_paths) > 0)) or match_json, \
     "Missing either a list of input image paths or a match json"

    if not img_paths or len(img_paths) == 0:
        step_count = match_json["step_count"]

        for step in match_json["steps"][:step_count]:
            print("Step: %s" % step["name"])
            img_paths.append(step["path"])

    # TODO: Allow any matcher type and number of images...
    assert len(img_paths) == 1 or len(img_paths) == 11, \
     "Invalid number of images %d, expected 2 or 11" % len(img_paths)

    for img_path in img_paths:
        print img_path
        imgs.append(Image(filename=img_path))

    mpos = lambda w: (img.width - w) / 2

    if len(img_paths) == 1:
        img.caption(caption,
                    left=(img.width - 250) / 2,
                    top=5,
                    width=250,
                    height=100,
                    font=font_title)
        img.composite(imgs[0], left=mpos(imgs[0].width), top=120)
        return img

    orgimg = imgs[0]  # Original image.
    detected = imgs[1]  # Detected cat head roi.
    croproi = imgs[2]  # Cropped/extended roi.
    globalthr = imgs[3]  # Global threshold (inverted).
    adpthr = imgs[4]  # Adaptive threshold (inverted).
    combthr = imgs[5]  # Combined threshold.
    opened = imgs[6]  # Opened image.
    dilated = imgs[7]  # Dilated image.
    combined = imgs[8]  # Combined image (re-inverted).
    contours = imgs[9]  # Contours of white areas.
    final = imgs[10]  # Final image.

    # TODO: Enable creating these based on input instead.
    kernel3x3 = create_kernel(w=3, h=3)
    kernel2x2 = create_kernel(w=2, h=2)
    kernel5x1 = create_kernel(w=5, h=1)

    x_start = 20

    img.caption(caption,
                left=(img.width - 250) / 2,
                top=5,
                width=250,
                height=100,
                font=font_title)

    if description:
        desc_font = Font(path="%s/source-code-pro/SourceCodePro-Medium.otf" %
                         font_path,
                         size=24)
        text_width = (desc_font.size) * int(len(description) * 0.7)
        img.caption(description,
                    left=(img.width - text_width) / 2,
                    top=80,
                    width=text_width,
                    height=100,
                    font=desc_font)

    height = 120

    # Original.
    img.composite(orgimg, left=mpos(orgimg.width), top=height)
    height += orgimg.height + gap

    # Detected head + cropped region of interest.
    head_row = create_row([detected, croproi], [0, 0],
                          horizontal_gap,
                          caption="Detected head  Cropped ROI")
    img.composite(head_row, left=mpos(head_row.width), top=height)
    height += head_row.height + gap

    # TODO: simplify the code below by making the symbols into images before they're used to create the rows.

    # Combine the threshold images.
    thr_row = create_row(
        [globalthr, "+", adpthr, "=", combthr], [
            x_start, (4 * horizontal_gap, -15, 14 * horizontal_gap, font), 0,
            (2 * horizontal_gap, -15, 8 * horizontal_gap, font),
            2 * horizontal_gap
        ],
        horizontal_gap,
        fixed_width=img.width,
        caption=
        "Global Threshold           Adaptive Threshold       Combined Threshold",
        caption_offset=(x_start, 0))
    img.composite(thr_row, left=mpos(thr_row.width), top=height)
    height += thr_row.height + gap

    # Open the combined threshold.
    open_row = create_row(
        [combthr, u"∘", kernel2x2, "=", opened], [
            x_start,
            (5 * horizontal_gap, -5, 14 * horizontal_gap, font_math), 0,
            (21 * horizontal_gap, -15, 10 * horizontal_gap, font),
            19 * horizontal_gap + 3
        ],
        horizontal_gap,
        fixed_width=img.width,
        caption=
        "Combined Threshold         2x2 Kernel               Opened Image",
        caption_offset=(x_start, 0))
    img.composite(open_row, left=mpos(open_row.width), top=height)
    height += open_row.height + gap

    # Dilate opened and combined threshold with a kernel3x3.
    dilated_row = create_row(
        [opened, u"⊕", kernel3x3, "=", dilated], [
            x_start,
            (3 * horizontal_gap, -5, 14 * horizontal_gap, font_math), 0,
            (17 * horizontal_gap, -15, 10 * horizontal_gap, font),
            15 * horizontal_gap + 3
        ],
        horizontal_gap,
        fixed_width=img.width,
        caption=
        "Opened Image               3x3 Kernel               Dilated Image",
        caption_offset=(x_start, 0))
    img.composite(dilated_row, left=mpos(dilated_row.width), top=height)
    height += dilated_row.height + gap

    # Inverted image and contour.
    contour_row = create_row([combined, contours], [0, 0],
                             horizontal_gap,
                             caption="  Re-Inverted         Contours")
    img.composite(contour_row, left=mpos(contour_row.width), top=height)
    height += contour_row.height + 2 * gap

    # Final.
    img.composite(final, left=mpos(final.width), top=height)
    height += final.height + gap

    return img
Example #30
0
def test_string():
    assert Color('black').string in ('rgb(0,0,0)', 'srgb(0,0,0)')
    assert str(Color('black')) in ('rgb(0,0,0)', 'srgb(0,0,0)')
Example #31
0
def test_equals():
    """Equality test."""
    assert Color('#fff') == Color('#ffffff') == Color('white')
    assert Color('#000') == Color('#000000') == Color('black')
    assert Color('rgba(0, 0, 0, 0)') == Color('rgba(0, 0, 0, 0)')
    assert Color('rgba(0, 0, 0, 0)') == Color('rgba(1, 1, 1, 0)')
Example #32
0
def hide_notify_tag(image):
    with Image(width=130, height=50, background=Color('white')) as cover:
        if image.colorspace == 'cmyk':
            cover.transform_colorspace('cmyk')
        image.composite(cover, left=0, top=0)
Example #33
0
def test_red():
    assert Color('black').red == 0
    assert Color('red').red == 1
    assert Color('white').red == 1
    assert 0.5 <= Color('rgba(128, 0, 0, 1)').red < 0.51
Example #34
0
import sys
from wand.color import Color
from wand.image import Image

if len(sys.argv) < 3:
    print('{0} <ORIGINAL PATH> <DEGREE> [BACKGROUND]'.format(sys.argv[0]))
    sys.exit()

original_path=sys.argv[1]
degree=int(sys.argv[2])
bgcolor='#FFFFFF' #사용자가 배경색을 지정하지 않으면 흰색

if len(sys.argv) > 3:
    bgcolor=sys.argv[3]

with Image(filename=original_path) as image:
    with image.clone() as rotated:
        rotated.rotate(degree, background=Color(bgcolor)) #이미지 회전
        rotated.save(filename=str(degree)+'_'+original_path)


Example #35
0
def test_blue():
    assert Color('black').blue == 0
    assert Color('blue').blue == 1
    assert Color('white').blue == 1
    assert 0.5 <= Color('rgba(0, 0, 128, 1)').blue < 0.51
    with Image(img, resolution=200) as img:
        print("Processing Page " + (x + 1).__str__())
        img.compression_quality = 99
        img.type = 'grayscale'
        img.resize(3700, 5000)
        img.crop(1, 1, 3550, 4800)
        # img.level(0.5, 0.9, gamma=1.66)
        # img.level(0.5, 0.7, gamma=1.0)

        # Better one (Level)
        img.level(0.6, 0.8, gamma=2.00)

        img.trim(fuzz=40)
        img.normalize(channel=None)
        img.modulate(saturation=50)
        img.background_color = Color("white")
        # img.image_median = 1
        # img.image_contrast = 100

        # img.contrast_stretch(1.0, 0.0, "black")
        # img.linear_stretch(0.1, 1.0)
        # img.type = 'bilevel'

        img.save(filename=directory_path + '/Images/grayscale.png')
        # img.save(filename='E:/last/Images/grayscale.png')

    # print(type(img))

    # ########################## Gaussian Filter ##########################
    kernel = np.array([[-1, -1, -1, -1, -1], [-1, 2, 2, 2, -1],
                       [-1, 2, 8, 2, -1], [-2, 2, 2, 2, -1],
Example #37
0
def test_red_int8():
    assert Color('black').red_int8 == 0
    assert Color('red').red_int8 == 255
    assert Color('white').red_int8 == 255
    assert Color('rgba(128, 0, 0, 1)').red_int8 == 128
Example #38
0
def DebugExtract(path, out):
    # Load pdf
    laparams = LAParams()
    rsrcmgr = PDFResourceManager()
    document = file(path, 'rb')
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)

    for i, page in enumerate(PDFPage.get_pages(document)):
        # Get page layout
        interpreter.process_page(page)
        layout = device.get_result()

        textboxes = [r for r in layout._objs if type(r) is LTTextBoxHorizontal]
        rects = [r for r in layout._objs if type(r) is LTRect]
        lines = [r for r in layout._objs if type(r) is LTLine]

        page_path = "{}[{}]".format(path, i)
        print i
        with Drawing() as draw:
            with Image(filename=page_path) as img:
                with Image(width=img.width,
                           height=img.height,
                           background=Color("white")) as background:
                    background.composite(img, 0, 0)

                    # Draw rectangles
                    draw.fill_color = Color("transparent")

                    totals = []
                    for txt in textboxes:
                        # print repr(txt.get_text())
                        if txt.get_text() in ["Total \n", "Marks  Total \n"]:
                            print "found total..."
                            totals.append(txt)
                    if len(totals) == 1:
                        totals.append(totals[0])

                    def draw_rects(objs, color):
                        draw.stroke_color = Color(color)
                        for obj in objs:
                            top = img.height - obj.y0
                            bottom = img.height - obj.y1
                            draw.rectangle(left=obj.x0,
                                           top=bottom,
                                           right=obj.x1,
                                           bottom=top)

                    # draw_rects(textboxes, "red")
                    boxes = []
                    box_count = len(totals) / 2
                    if len(rects) > 0:
                        for b in range(box_count):
                            print b
                            big = 1000000
                            x0 = big
                            # y0 = big
                            # ymax = big
                            # if b < box_count-1:
                            #     ymax = img.height - totals[b+2].y0
                            x1 = 0
                            # y1 = totals[0].y1
                            # if b < box_count-1:
                            #     y1 = totals[b+1].y0
                            ymin = 55
                            ymax = big

                            y0 = img.height - totals[b * 2].y1
                            y1 = img.height - totals[b * 2 + 1].y0

                            if b < box_count - 1:
                                # Ensures the bottom of this block is above the next box
                                ymax = img.height - totals[(b + 1) * 2].y1

                            if b > 0:
                                # Ensures that the top of this box is bellow the last box
                                ymin = boxes[-1][3] + 1

                            print y0, y1, ymin, ymax

                            # ymax = big
                            # if b < box_count-1:
                            #     ymax = totals[(b+1)*2].y1

                            # print "before:"
                            # print x0, y0, x1, y1, ymax

                            for r in rects:
                                x0 = min(r.x0, x0)
                                x1 = max(r.x1, x1)
                                if (img.height - r.y0) > ymin:
                                    y0 = min(img.height - r.y0, y0)
                                if (img.height - r.y1) < ymax:
                                    y1 = max(img.height - r.y1, y1)

                            # print "after:"
                            # print x0, y0, x1, y1

                            boxes.append((x0, y0, x1, y1))

                        if box_count > 0:
                            foo = 0
                            for (x0, y0, x1, y1) in boxes:
                                if foo == 0:
                                    draw.stroke_color = Color("green")
                                    draw.stroke_width = 1
                                elif foo == 1:
                                    draw.stroke_color = Color("red")
                                    draw.stroke_width = 1
                                foo += 1
                                draw.rectangle(left=x0,
                                               top=y0,
                                               right=x1,
                                               bottom=y1)

                        # if y1 > y0 and len(totals) > 0:
                        # draw.stroke_color = Color("green")
                        # draw.rectangle(left=x0, top=img.height-y1, right=x1, bottom=img.height-y0)
                        # draw.stroke_color = Color("blue")
                        # draw.rectangle(left=x0, top=img.height-totals[0].y1, right=x1, bottom=img.height-y0)

                    # draw_rects(rects, "blue")
                    draw(background)

                    background.save(
                        filename=os.path.join(out, "t{}.png".format(i)))
Example #39
0
def test_blue_int8():
    assert Color('black').blue_int8 == 0
    assert Color('blue').blue_int8 == 255
    assert Color('white').blue_int8 == 255
    assert Color('rgba(0, 0, 128, 1)').blue_int8 == 128
Example #40
0
def test_cyan():
    assert Color('cmyk(100%, 0, 0, 0)').cyan == 1
    assert Color('cmyk(0, 0, 0, 0)').cyan == 0
    c = Color('none')
    c.cyan = 1
    assert c.cyan == 1
Example #41
0
    if i == 3:
        return img[:, intensity:]


print args
if not os.path.isdir('./frames'):
    os.mkdir('./frames')

with Image(file=open(args.image)) as img:
    gif = img.convert('gif')
    for x in range(4):
        frame = gif.clone()
        if args.wiggle:
            frame = cropshift(x, frame,
                              int(args.intensity) if args.intensity else 20)
        color = Color('#FFFFFF')
        if args.flash_text and (x == 1 or x == 3):
            color = Color('FF0000')
        if (args.text):
            frame.caption(text=args.text,
                          font=Font("./Impact.ttf", 48, color),
                          gravity='south')
        frame.save(filename=('./frames/%d.gif' % x))

subprocess.call([
    'convert', '-dispose', 'none', '-delay',
    str((5 - (float(args.speed) if args.speed else 3)) + 1.5),
    './frames/*.gif', '-coalesce', '-loop', '0',
    args.outfile if args.outfile else 'out.gif'
])
Example #42
0
def test_magenta():
    assert Color('cmyk(0, 100%, 0, 0)').magenta == 1
    assert Color('cmyk(0, 0, 0, 0)').magenta == 0
    c = Color('none')
    c.magenta = 1
    assert c.magenta == 1
Example #43
0
def draw_type_one(draw, width):
    if config['mark_color'] == "":
        draw.stroke_color = Color(green)
    spacing = 100 if (width != 2560) else 118
    draw.circle((CCPX + spacing * (current_day - 1), CCPY),
                (CPPX + spacing * (current_day - 1), CPPY))
Example #44
0
def test_yellow():
    assert Color('cmyk(0, 0, 100%, 0)').yellow == 1
    assert Color('cmyk(0, 0, 0, 0)').yellow == 0
    c = Color('none')
    c.yellow = 1
    assert c.yellow == 1
Example #45
0
def generate(file_in, file_out, lin, win, mac):
    """
    Generate a Steam CD. This function calls a shell script to do the circular
    crop. TODO: implement circular cropping with Wand for platform independence.
    """

    platform = "%s/platform-%s.png" % (PATH, ('l' if lin else '') +
                                       ('w' if win else '') +
                                       ('m' if mac else ''))

    # Circular crop the header to a temporary file
    call([
        "sh",
        "%s/steam-crop.sh" % PATH, file_in, '/tmp/crop.png',
        str(RADIUS),
        str(V_OFFSET)
    ])

    with Image(filename='/tmp/crop.png') as header,                            \
            Image(filename="%s/disc.png" % PATH) as disc,                      \
            Image(width=disc.width, height=disc.height) as cd:

        if not (header.width, header.height) == HEADER_SIZE:
            return

        # Compute the best border color
        border = 'rgb' + str(color_average(header))

        # Draw upper semi-circle
        with Drawing() as draw:
            draw.fill_color = Color(border)
            draw.ellipse((disc.width // 2, disc.height // 2), (RADIUS, RADIUS),
                         (180, 0))
            draw(cd)

        # Draw lower semi-circle
        with Drawing() as draw:
            draw.fill_color = Color('black')
            draw.ellipse((disc.width // 2, disc.height // 2), (RADIUS, RADIUS),
                         (0, 180))
            draw(cd)

        # Composite header
        with Drawing() as draw:
            draw.composite(operator='over',
                           left=-10,
                           top=84,
                           width=header.width,
                           height=header.height,
                           image=header)
            draw(cd)

        # Composite platform
        if lin or win or mac:
            with Drawing() as draw, Image(filename=platform) as plat:
                draw.composite(operator='over',
                               left=(cd.width - plat.width) // 2,
                               top=330,
                               width=plat.width,
                               height=plat.height,
                               image=plat)
                draw(cd)

        # Composite edge
        with Drawing() as draw:
            draw.composite(operator='over',
                           left=0,
                           top=0,
                           width=disc.width,
                           height=disc.height,
                           image=disc)
            draw(cd)

        # Draw CD hole
        with Drawing() as draw, Image(width=disc.width,
                                      height=disc.height) as hole:
            draw.circle(((disc.width // 2) - 1, (disc.height // 2) - 1),
                        (disc.width // 2, (disc.height // 2) + HOLE))
            draw(hole)

            draw.composite(operator='dst_out',
                           left=0,
                           top=0,
                           width=hole.width,
                           height=hole.height,
                           image=hole)
            draw(cd)

        # Write final image
        cd.save(filename=file_out)
Example #46
0
def test_set_get_stroke_color(fx_wand):
    with Color('#333333') as black:
        fx_wand.stroke_color = black
    assert fx_wand.stroke_color == Color('#333333')
    fx_wand.stroke_color = 'skyblue'
    assert fx_wand.stroke_color == Color('SkyBlue')
def convert(filename, file_width, file_height, page_number, pdf_location,
            file_hash, execution_start_time, log_dictionary, uploaded_file_id,
            process_start_time, thumbnail_id):
    """
		This function converts a single Page PDF into a high resolution image and adds the details into the 'image' table
		Input: A Single Page PDF/Image
		Output: A High Resolution Image
	"""

    from wand.image import Image
    from wand.color import Color
    import os
    from database import login_info
    import mysql.connector
    import config
    from PIL import Image as pilImage
    import convert_to_tiles
    import time

    db = mysql.connector.Connect(**login_info)
    cursor = db.cursor()
    png_blob = "NULL"
    pdf_blob = "NULL"
    if not os.path.exists(config.store_high_res_images):
        os.makedirs(config.store_high_res_images)
    with Image(filename=filename, resolution=config.high_res_value) as img:
        with Image(width=img.width,
                   height=img.height,
                   background=Color("white")) as bg:
            bg.composite(img, 0, 0)
            bg.save(filename=config.store_high_res_images +
                    filename.replace(config.store_split_pdfs, "") + ".png")

    im = pilImage.open(config.store_high_res_images +
                       filename.replace(config.store_split_pdfs, "") + ".png")
    img_width, img_height = im.size

    page_size = str(file_width) + "," + str(file_height)

    if config.add_high_res_png_into_db == 1:
        with open(
                config.store_high_res_images +
                filename.replace(config.store_split_pdfs, "") + ".png",
                "rb") as img:
            png_blob = img.read()

    if config.add_split_pdf_into_database == 1:
        with open(pdf_location, "rb") as pdf:
            pdf_blob = pdf.read()

    # sql_query = """INSERT INTO `image` (`id`, `album_id`, `user_id`, `upload_file_id`, `thumbnail_id`,`page_size`, `png`, `pdf`, `width`, `height`, `page_number`) VALUES (NULL, NULL, NULL, '""" + upload_file_id + """', '""" + str(thumbnail_id) + """', '""" + page_size + """', '""" + png_blob + """' , '""" + pdf_blob + """', '""" + str(img_width) + """', '""" + str(img_height) + """', '""" + str(page_number) + """');"""
    cursor.execute(
        "INSERT INTO `image`(upload_file_id, thumbnail_id, page_size, png, pdf, width, height, page_number) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);",
        (uploaded_file_id, str(thumbnail_id), page_size, png_blob, pdf_blob,
         img_width, img_height, ""))
    db.commit()
    cursor.close()
    db = mysql.connector.Connect(**login_info)
    cursor = db.cursor()
    sql_query = """SELECT * FROM `image` WHERE upload_file_id LIKE '%s' AND page_number LIKE '%s'""" % (
        uploaded_file_id, str(page_number))
    cursor.execute(sql_query)
    current_image_id = 0
    for row in cursor:
        current_image_id = row[0]
        break
    cursor.close()
    process_end_time = time.time()

    total_time = str(
        round(process_end_time - process_start_time,
              config.time_digit_precision))
    print(
        "[" + str(uploaded_file_id) + "," + str(page_number) +
        "] High Resolution PNG Generated. Details Added to 'image' table. Time: "
        + total_time)
    config.write_to_file(
        config.log_file_name,
        "[" + str(uploaded_file_id) + "," + str(page_number) +
        "] High Resolution PNG Generated. Details Added to 'image' table. Time: "
        + total_time)
    log_dictionary['all_steps'] += "[" + str(
        page_number
    ) + "] High Resolution PNG Generated Details Added to 'image' table. Time: " + total_time + "\n"
    log_dictionary = convert_to_tiles.generate_tiles(
        config.store_high_res_images +
        filename.replace(config.store_split_pdfs, "") + ".png",
        current_image_id, log_dictionary, page_number, uploaded_file_id,
        time.time())
    return log_dictionary
Example #48
0
def bord(p, size=15, color='black'):
    p._im.resize(p._im.width - size * 2, p._im.height - size * 2)
    p._im.border(Color(color), size, size)
    return p
Example #49
0
    async def _compose_alvise(self, bg_img, text=None, count=1, **kwargs):
        with Drawing() as drawing:
            # fill the drawing primitives
            drawing.font = 'assets/HelveticaNeueLTCom-Md.ttf'
            drawing.gravity = 'north_west'
            drawing.fill_color = Color('#56fdb4')
            text = text if text else '@Alvisepf'

            # try to determine what a good font size would be
            string_list = text.split('\n')
            longest_string = len(max(string_list, key=len))
            line_count = len(string_list)
            drawing.font_size = max(
                min(bg_img.width / longest_string * 1.5,
                    bg_img.height / line_count * 1.5), 4)

            # the drawing has some padding so ascenders and descenders do not get truncated
            metrics = drawing.get_font_metrics(bg_img, text, '\n' in text)
            mask_w_orig, mask_h_orig = metrics.text_width, metrics.text_height + metrics.descender
            mask_w, mask_h = int(mask_w_orig * 1.02), int(mask_h_orig * 1.1)
            drawing.text(int((mask_w - mask_w_orig) / 2),
                         int((mask_h - mask_h_orig) / 2), text)

            # create a mask image to draw the text on to, and...
            with Image(width=mask_w, height=mask_h) as mask_img:
                # draw the text into the mask image
                drawing.draw(mask_img)
                original_mask_img = Image(mask_img)

                frames = []
                for i in range(count):
                    mask_img = Image(original_mask_img)
                    # rotate the mask
                    mask_img.rotate(random.uniform(-35, -5))
                    # calculate what a smaller background image would look like
                    scaling_factor = random.uniform(.5, .7)
                    bg_img_scaled_w = bg_img.width * scaling_factor
                    bg_img_scaled_h = bg_img.height * scaling_factor
                    # scale the mask to fit into that smaller background image
                    mask_img.transform(resize='%dx%d' %
                                       (bg_img_scaled_w, bg_img_scaled_h))
                    # calculate a random position inside the background image for it
                    offset_left = random.randint(0,
                                                 bg_img.width - mask_img.width)
                    offset_top = random.randint(
                        0, bg_img.height - mask_img.height)
                    # and put the mask in the image
                    bg_img.composite(mask_img,
                                     left=offset_left,
                                     top=offset_top)

                    frames.append(
                        self.save_image(
                            self.generate_filename(self.filename, i)))

                    if kwargs.get('callback') and kwargs.get('callback_args'):
                        await kwargs.get('callback')(
                            kwargs.get('callback_args')[0], i, count)

                original_mask_img.destroy()

        return frames
Example #50
0
#         -stroke black -annotate +193+59 o  -stroke none -annotate +193+59 o \
#         -stroke black -annotate +225+59 n  -stroke none -annotate +225+59 n \
#         -stroke black -annotate +266+54 y  -stroke none -annotate +266+54 y \
#         font_jittered.jpg


def drawcharacter(draw, char, x, y, color):
    draw.stroke_color = color
    draw.text(x, y, char)
    draw.stroke_color = Color('none')
    draw.text(x, y, char)


w = 320
h = 100
with Image(width=w, height=h, background=Color('lightblue')) as img:
    with Drawing() as draw:
        draw.font = 'Candice'
        draw.font_size = 72
        draw.gravity = 'forget'
        draw.fill_color = Color('white')
        draw.stroke_width = 4
        drawcharacter(draw, 'A', 26, 80, Color('black'))
        drawcharacter(draw, 'n', 95, 63, Color('black'))
        drawcharacter(draw, 't', 133, 54, Color('black'))
        drawcharacter(draw, 'h', 156, 67, Color('black'))
        drawcharacter(draw, 'o', 193, 59, Color('black'))
        drawcharacter(draw, 'n', 225, 59, Color('black'))
        drawcharacter(draw, 'y', 266, 54, Color('black'))
        draw(img)
        img.save(filename='sample21.png')
Example #51
0
#
# convert path_cubic_canvas.gif  -fill white -stroke black \
#         -draw "path 'M 10,30  C 10,4 50,4 50,30  S 90,55 90,30' " \
#         path_cubic.gif


def draw_control(draw, base, to, r, fill=True):
    draw.push()
    if not fill:
        draw.fill_color = Color('none')
    draw.line(base, to)
    draw.circle(to, (to[0], to[1] - r))
    draw.pop()


with Image(width=100, height=60, background=Color('skyblue')) as img:
    with Drawing() as draw:
        draw.fill_color = Color('white')
        draw.stroke_color = Color('black')
        draw.path_start()
        draw.path_move((10, 30))
        draw.path_curve(controls=[(10, 4), (50, 4)], to=(50, 30))
        draw.path_curve(smooth=True, controls=(90, 55), to=(90, 30))
        draw.path_finish()

        draw.fill_color = Color('dodgerblue')
        draw.stroke_color = Color('dodgerblue')
        draw_control(draw, (10, 30), (10, 4), 3)
        draw_control(draw, (50, 30), (50, 4), 3)
        draw_control(draw, (50, 30), (50, 56), 3, False)
        draw_control(draw, (90, 30), (90, 56), 3)
Example #52
0
def drawcharacter(draw, char, x, y, color):
    draw.stroke_color = color
    draw.text(x, y, char)
    draw.stroke_color = Color('none')
    draw.text(x, y, char)
Example #53
0
#!/usr/bin/env python

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color
from wandplus.textutil import calcSuitableImagesize

# http://www.imagemagick.org/Usage/fonts/
# original imagemagick command:
#  convert -font Candice -pointsize 32 -background lightblue \
#          -fill navy label:"Anthony's IM Examples" \
#          -virtual-pixel background  -distort Arc 340 \
#          font_circle.jpg

with Drawing() as draw:
    text = 'Anthony\'s IM Examples'
    draw.font = 'Candice'
    draw.font_size = 32
    draw.gravity = 'center'
    (w, h) = calcSuitableImagesize(draw, text)
    with Image(width=w, height=h, background=Color('lightblue')) as img:
        draw.fill_color = Color('navy')
        draw.text(0, 0, text)
        draw(img)
        img.distort('arc', [340], False)
        img.save(filename='sample33.png')
Example #54
0
def test_black():
    assert Color('cmyk(0, 0, 0, 100%)').black == 1
    assert Color('cmyk(0, 0, 0, 0)').black == 0
    c = Color('none')
    c.black = 1
    assert c.black == 1