コード例 #1
0
ファイル: main.py プロジェクト: malcx95/rc-telemetry-composer
def add_telemetry_data(get_frame, t):
    offset = SENSOR_DATA.time_offset
    frame = get_frame(t)
    height, _, _, = frame.shape
    global FONT
    global SMALL_FONT
    global TEXT_FRAME
    global THROTTLE_BAR
    global STEERING_BAR
    if FONT is None:
        FONT = ImageFont.FreeTypeFont("../fonts/PEPSI_pl.ttf", int(FONT_SIZE*(height/1440)))
        SMALL_FONT = ImageFont.FreeTypeFont("../fonts/PEPSI_pl.ttf", int(SMALL_FONT_SIZE*(height/1440)))
        TEXT_FRAME = get_static_text(frame.shape)
        THROTTLE_BAR = prepare_throttle_bar(frame)
        STEERING_BAR = prepare_steering_bar(frame)

    add_speed_text(frame, SENSOR_DATA.speed(t))
    add_throttle_bar(frame, SENSOR_DATA.throttle(t), np.copy(THROTTLE_BAR))
    add_steering_bar(frame, SENSOR_DATA.steering(t), np.copy(STEERING_BAR))
    #add_steering_bar(frame, -1.0, np.copy(STEERING_BAR))

    overlay_image(frame, TEXT_FRAME, 0, 0)
    #plt.figure(1)
    #plt.imshow(frame)
    #plt.show()
    #sys.exit(0)
    return frame
コード例 #2
0
    def tex(self, xml_node=None, name=None):
        if name == None:
            children_count = len(xml_node)
            if children_count > 0:
                text = xml_node.get('name') + " >"
            else:
                text = xml_node.get('name')
        else:
            text = name

        image_size = [400, 100]  ## size of the image of the button
        outline_width = 10
        inner_size = [
            image_size[0] - outline_width, image_size[1] - outline_width
        ]

        ## blank button creation (eventually the outline)
        img = Image.new("RGBA", image_size, self.outline_color)
        draw = ImageDraw.Draw(img)

        ## draw inner color
        x0 = outline_width
        y0 = outline_width
        x1 = inner_size[0]
        y1 = inner_size[1]
        draw.rectangle([x0, y0, x1, y1], fill=self.button_color)

        ## add text only if not root button
        if text != "":
            ## font information for the text
            font_size = 1
            f = ImageFont.FreeTypeFont("font.ttf", font_size)
            y = f.getoffset(text)[1]
            wh = f.getsize(text)  ## size of the text in the current font

            while (wh[0] < inner_size[0] - outline_width) and (
                    wh[1] < inner_size[1] - outline_width - y):
                font_size += 1
                f = ImageFont.FreeTypeFont("font.ttf", font_size)
                y = f.getoffset(text)[1]
                wh = f.getsize(text)  ## size of the text in the current font

            font_size -= 2
            f = ImageFont.FreeTypeFont("font.ttf", font_size)
            y = f.getoffset(text)[1]
            wh = f.getsize(text)  ## size of the text in the current font

            ## calculate top-left corner of text in order to center it
            tx = ((outline_width + inner_size[0]) / 2) - wh[0] / 2
            ty = ((outline_width + inner_size[1] - 2 * y) / 2) - wh[1] / 2

            ## add text to the button (name)
            draw.text([tx, ty], text, self.outline_color, font=f)

        ## rotate the finished product
        img = img.rotate(180)
        img = img.transpose(PIL.Image.FLIP_LEFT_RIGHT)

        return img
コード例 #3
0
    def create_image(self):
        # generate qr
        big_code = pyqrcode.create(self.id)
        big_code.png('tmp_code.png',
                     scale=20,
                     module_color=[0, 0, 0, 128],
                     background=(255, 255, 255))

        qr = Image.open("tmp_code.png")
        ticket_width = qr.width + 60

        # get qr img
        qr_img = Image.new('RGB', (ticket_width, ticket_width),
                           color=(255, 218, 0))
        qr_img.paste(qr, (30, 30))

        # get text img
        text_img = Image.new('RGB', (ticket_width, 420), color=(255, 218, 0))
        d = ImageDraw.Draw(text_img)
        master_font = ImageFont.FreeTypeFont('fonts/HelveticaBlack.ttf',
                                             60,
                                             encoding="utf-8")
        d.text((50, 50),
               "BadFest 2022 / 2-3 июля",
               fill=(0, 0, 0),
               font=master_font)
        slave_font = ImageFont.FreeTypeFont('fonts/arial.ttf',
                                            40,
                                            encoding="utf-8")
        d.text((60, 130),
               'Имя: ' + self.user.real_name,
               fill=(0, 0, 0),
               font=slave_font)
        d.text((60, 180),
               'Тип: ' + self.ticket_name,
               fill=(0, 0, 0),
               font=slave_font)
        d.text((60, 230),
               'Стоимость: ' + str(self.total_amount / 100) + ' рублей',
               fill=(0, 0, 0),
               font=slave_font)
        d.text((60, 280),
               'Дата: ' + self.created + ' (UTC)',
               fill=(0, 0, 0),
               font=slave_font)

        # get ticket size
        ticket_height = qr_img.height + text_img.height

        # concatenate text and qr
        purchase = Image.new('RGB', (ticket_width, ticket_height))
        purchase.paste(text_img, (0, 0))
        purchase.paste(qr_img, (0, text_img.height))

        purchase.save(f'images/{self.id}.png')
コード例 #4
0
def mocked(string, output):
    image = Image.open("mock.jpg", 'r')
    width, height = image.size
    rell, tamstri = 0, 0
    drawing = ImageDraw.Draw(image)

    def draw_shadow(off, argfont, estring, pix):
        drawing.text((off[0] - pix, off[1] - pix),
                     estring,
                     font=argfont,
                     fill='black')
        drawing.text((off[0] + pix, off[1] - pix),
                     estring,
                     font=argfont,
                     fill='black')
        drawing.text((off[0] - pix, off[1] + pix),
                     estring,
                     font=argfont,
                     fill='black')
        drawing.text((off[0] + pix, off[1] + pix),
                     estring,
                     font=argfont,
                     fill='black')

    if isinstance(string, u"".__class__):

        tamstri = len(string)
        rell = width // (int((tamstri) / 2.12))
        if rell > 200:
            rell = height // int(tamstri)
        offset = [width // rell, height - rell - 10]
        font = ImageFont.FreeTypeFont('impact.ttf', size=rell)
        draw_shadow(offset, font, string, 2)
        drawing.text(offset, string, font=font)

    elif isinstance(string, list):
        offset = [20, height - height // 4]
        maxlen = 0
        for elem in string:
            tamstri += len(elem)
            if maxlen < len(elem):
                maxlen = len(elem)
        rell = width // (int(maxlen / 2.12))
        if rell > 90:
            rell = height // int(maxlen)
        font = ImageFont.FreeTypeFont('impact.ttf', size=rell)

        for line in string:
            draw_shadow(offset, font, line, 2)
            drawing.text(offset, line, font=font)
            offset[1] += rell
    image.save(output)
コード例 #5
0
def main(mode, face_id_model_root, id_features_dir, font_path):
    print('Loading models...')
    det_models = load_detect_faces_models()
    face_id_model = load_face_id_model(model_root=face_id_model_root)
    id_npy = load_id_files(id_features_dir)
    crop_size = 112
    max_size = 1024
    reference = get_reference_facial_points(default_square=True)
    font = ImageFont.FreeTypeFont(font=font_path, size=24)

    print('Starting image processing...')
    if mode == Mode.DEMO:
        demo(det_models=det_models,
             face_id_model=face_id_model,
             reference=reference,
             crop_size=crop_size,
             id_npy=id_npy,
             max_size=max_size,
             font=font)
    elif mode == Mode.FILE:
        process_files(input_dir=STREAM_DIR,
                      output_dir=RESULT_DIR,
                      det_models=det_models,
                      face_id_model=face_id_model,
                      reference=reference,
                      crop_size=crop_size,
                      id_npy=id_npy,
                      max_size=max_size,
                      font=font)
    else:
        raise ValueError('Invalid mode: {}'.format(mode))
コード例 #6
0
def load_data(image_id, requested_size):
    """ Manipulate marker images to display the cost as well """

    if requested_size != "":
        pass

    brand, cost, colour, fontsize = image_id.split('%7C')
    marker = "assets/" + brand + ".png"
    bg_img = Image.new("RGBA", (65, 90), (255, 0, 0, 0))
    marker = Image.open(marker).convert("RGBA")
    bg_img.paste(marker, (0, 31), marker)

    draw = ImageDraw.Draw(bg_img)
    if colour == "blue":
        draw.rectangle(((0, 0), (65, 31)), fill=(0, 70, 126))
    else:
        draw.rectangle(((0, 0), (65, 31)), fill=(202, 30, 46))

    font = ImageFont.FreeTypeFont("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf", \
                                  size=int(fontsize))

    if "." not in cost:
        cost += ".0"

    draw.text((4, 4), cost, font=font)

    binimg = io.BytesIO()
    bg_img.save(binimg, 'png')
    return bytearray(binimg.getvalue()), (-1, -1), pyotherside.format_data
コード例 #7
0
def tagErrorImage(failimg, location, camname=None):
    """
    Given the failure image filename, add a timestamp to it
    starting at the specified pixel location (lower left corner of text).

    Leaving this hardcoded for now since it is something that's probably
    deployment dependent, but it could be abstracted with work/effort.

    Will save the resulting image to location when it's done.
    """
    font = ImageFont.FreeTypeFont('./fonts/GlacialIndifference-Bold.otf',
                                  size=24,
                                  encoding='unic')

    timestamp = dt.utcnow()
    timestring = timestamp.strftime("%Y-%m-%d %H:%M:%S UTC")

    img = Image.open(failimg)
    dtxt = ImageDraw.Draw(img)

    # We don't actually need the height since I eyeballed it
    tw, _ = font.getsize(timestring)
    ntw = 170 - tw // 2

    dtxt.text((ntw, 200), timestring, fill=(255, 76, 76), font=font)

    if camname is not None:
        # Same as above
        tw, _ = font.getsize(camname)
        ntw = 170 - tw // 2
        dtxt.text((ntw, 85), camname, fill=(255, 76, 76), font=font)

    img.save(location)
コード例 #8
0
ファイル: render.py プロジェクト: yellowcrescent/catamap
    def __init__(self,
                 t_w,
                 t_h,
                 fontpath,
                 fontsize=24,
                 bg=(0, 0, 0, 255),
                 rendermode='text',
                 fpadding=4,
                 single=False):
        self.t_w = t_w
        self.t_h = t_h
        self.rmode = rendermode
        self.bg = bg
        self.fpadding = fpadding
        self.single = single

        try:
            self.font = ImageFont.FreeTypeFont(fontpath, size=fontsize)
            #self.lfont = self.font.font_variant(size=int(fontsize + 2))
            self.lfont = self.font.font_variant(size=(fontsize - 2))
            logger.debug("using font: %s (%s)", *self.font.getname())
        except Exception as e:
            logger.error("failed to open font '%s': %s", fontpath, str(e))

        self._init_image()
コード例 #9
0
ファイル: main.py プロジェクト: kudoff/LesyaDiary
async def cmd_schedule(message: types.Message):
    global students
    user_id = message.from_user.id
    student = students[user_id]
    font = ImageFont.FreeTypeFont('/home/ubuntu/sDiary/19572.TTF', 70)
    text_color = (150, 51, 72)
    img = Image.open('photo.jpg')
    draw = ImageDraw.Draw(img)

    for i in range(3):
        text_position_i = (280, 820 + i * 1080)
        for j in range(2):
            text_position_j = (text_position_i[0] + j * 1040, text_position_i[1])
            for z in range(7):
                text_position = (text_position_j[0], text_position_j[1] + z * 102)
                try:
                    text = student['grade']['schedule'][str(i + 3 * j)][z]
                    if len(text) > 12:
                        draw.text(text_position, text[:12] + '...', text_color, font)
                    else:
                        draw.text(text_position, text, text_color, font)
                except:
                    pass

    img.save('schedule_photo.jpg')

    with open('schedule_photo.jpg', 'rb') as photo:
        await message.answer_photo(photo)
コード例 #10
0
    def draw_scores_onto_image(self, img_disp):
        if self.scores is None:
            return

        for i in range(-1, len(self.action_labels)):
            fontpath = "/usr/share/fonts/truetype/lohit-malayalam/Lohit-Malayalam.ttf"
            font = ImageFont.FreeTypeFont(fontpath)
            FONT_SIZE = 0.7
            TXT_X = 20
            TXT_Y = 150 + i * 30
            COLOR_INTENSITY = 255
            utf_content = ""
            if i == -1:
                s = "P{}:".format(self.human_id)
            else:
                label = self.action_labels[i]
                if (label == 'stand'):
                    content = 'നിൽക്കുക'
                    utf_content = content.decode('utf-8')
                    s = "{:<5}: {:.2f}".format(utf_content, self.scores[i])
                else:
                    s = "{:<5}: {:.2f}".format(label, self.scores[i])
                COLOR_INTENSITY *= (0.0 + 1.0 * self.scores[i])**0.5

            cv2.putText(img_disp,
                        text=s,
                        org=(TXT_X, TXT_Y),
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale=FONT_SIZE,
                        color=(0, 0, int(COLOR_INTENSITY)),
                        thickness=2)
            img_pil = Image.fromarray(img_disp)
            draw = ImageDraw.Draw(img_pil)
            draw.text((TXT_X, TXT_Y), utf_content, font=font)
            img = np.array(img_pil)
コード例 #11
0
ファイル: fonts.py プロジェクト: shikhir-arora/Gisi
def im_font_from_io_font(font_io: io.BytesIO):
    font_io.seek(0)
    try:
        font = ImageFont.FreeTypeFont(font_io)
    except IOError:
        raise TypeError("Couldn't open font")
    font_io.seek(0)
    return font
コード例 #12
0
def get_one_pic(char, font_name='/Library/Fonts/华文中宋.ttf', font_size=50):
    font = ImageFont.FreeTypeFont(font_name, font_size)
    img = Image.new('RGB', (int(1.5 * font_size), int(1.5 * font_size)),
                    (255, 255, 255))
    draw = ImageDraw.Draw(img)
    draw.text((0, 0), char, (0), font=font)
    img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2GRAY)
    return img
コード例 #13
0
ファイル: photos.py プロジェクト: JackMcKew/jackmckew.dev
def watermark_photo(image, settings):
    margin = [10, 10]
    opacity = 0.6

    watermark_layer = Image.new("RGBA", image.size, (0, 0, 0, 0))
    draw_watermark = ImageDraw.Draw(watermark_layer)
    text_reducer = 32
    image_reducer = 8
    text_size = [0, 0]
    mark_size = [0, 0]
    text_position = [0, 0]

    if settings["PHOTO_WATERMARK_TEXT"]:
        font_name = "SourceCodePro-Bold.otf"
        default_font = os.path.join(DEFAULT_CONFIG["plugin_dir"], font_name)
        font = ImageFont.FreeTypeFont(default_font,
                                      watermark_layer.size[0] // text_reducer)
        text_size = draw_watermark.textsize(settings["PHOTO_WATERMARK_TEXT"],
                                            font)
        text_position = [
            image.size[i] - text_size[i] - margin[i] for i in [0, 1]
        ]
        draw_watermark.text(
            text_position,
            settings["PHOTO_WATERMARK_TEXT"],
            settings["PHOTO_WATERMARK_TEXT_COLOR"],
            font=font,
        )

    if settings["PHOTO_WATERMARK_IMG"]:
        mark_image = Image.open(settings["PHOTO_WATERMARK_IMG"])
        mark_image_size = [
            watermark_layer.size[0] // image_reducer for size in mark_size
        ]
        mark_image_size = (settings["PHOTO_WATERMARK_IMG_SIZE"]
                           if settings["PHOTO_WATERMARK_IMG_SIZE"] else
                           mark_image_size)
        mark_image.thumbnail(mark_image_size, Image.ANTIALIAS)
        mark_position = [
            watermark_layer.size[i] - mark_image.size[i] - margin[i]
            for i in [0, 1]
        ]
        mark_position = tuple([
            mark_position[0] - (text_size[0] // 2) + (mark_image_size[0] // 2),
            mark_position[1] - text_size[1],
        ])

        if not isalpha(mark_image):
            mark_image = mark_image.convert("RGBA")

        watermark_layer.paste(mark_image, mark_position, mark_image)

    watermark_layer = ReduceOpacity(watermark_layer, opacity)
    image.paste(watermark_layer, (0, 0), watermark_layer)

    return image
コード例 #14
0
def cfg_read_font(fnt: str, sz: int) -> ImageFont:
    if fnt is None:
        return ImageFont.load_default()
    elif len(fnt) != 0 and fnt[0] == ':':
        return ImageFont.load_path(fnt)
    else:
        try:
            return ImageFont.truetype(fnt[1:], sz)
        except OSError:
            return ImageFont.FreeTypeFont(fnt[1:], size=sz)
コード例 #15
0
ファイル: resources.py プロジェクト: uaraven/paperclock
    def __init__(self):
        self.big_font = ImageFont.FreeTypeFont(
            font='data/OpenSans-Bold.ttf', size=50)
        self.med_font = ImageFont.FreeTypeFont(
            font='data/OpenSans-SemiBold.ttf', size=20)
        self.small_font = ImageFont.FreeTypeFont(
            font='data/OpenSans-SemiBold.ttf', size=18)
        self.tiny_font = ImageFont.FreeTypeFont(
            font='data/OpenSans-Bold.ttf', size=14)

        self.larger_font = ImageFont.FreeTypeFont(
            font='data/OpenSans-Bold.ttf', size=25)

        # Icons
        self.sunrise = Image.open(
            'data/sunrise.png').convert(mode='1', dither=None)
        self.sunset = Image.open(
            'data/sunset.png').convert(mode='1', dither=None)

        self.icons = {}
コード例 #16
0
ファイル: photos.py プロジェクト: mfitzp/pelican-plugins
def watermark_photo(image, watermark_text, watermark_image,
                    watermark_image_size):

    margin = [10, 10]
    opacity = 0.6

    watermark_layer = Image.new("RGBA", image.size, (0, 0, 0, 0))
    draw_watermark = ImageDraw.Draw(watermark_layer)
    text_reducer = 32
    image_reducer = 8
    text_size = [0, 0]
    mark_size = [0, 0]
    font_height = 0
    text_position = [0, 0]

    if watermark_text:
        font_name = 'SourceCodePro-Bold.otf'

        plugin_dir = os.path.dirname(os.path.realpath(__file__))
        default_font = os.path.join(plugin_dir, font_name)
        font = ImageFont.FreeTypeFont(default_font,
                                      watermark_layer.size[0] // text_reducer)
        text_size = draw_watermark.textsize(watermark_text, font)
        text_position = [
            image.size[i] - text_size[i] - margin[i] for i in [0, 1]
        ]
        draw_watermark.text(text_position,
                            watermark_text, (255, 255, 255),
                            font=font)

    if watermark_image:
        mark_image = Image.open(watermark_image)
        mark_image_size = [
            watermark_layer.size[0] // image_reducer for size in mark_size
        ]
        mark_image.thumbnail(mark_image_size, Image.ANTIALIAS)
        mark_position = [
            watermark_layer.size[i] - mark_image.size[i] - margin[i]
            for i in [0, 1]
        ]
        mark_position = tuple([
            mark_position[0] - (text_size[0] // 2) + (mark_image_size[0] // 2),
            mark_position[1] - text_size[1]
        ])

        if not isalpha(mark_image):
            mark_image = mark_image.convert('RGBA')

        watermark_layer.paste(mark_image, mark_position, mark_image)

    watermark_layer = ReduceOpacity(watermark_layer, opacity)
    image.paste(watermark_layer, (0, 0), watermark_layer)

    return image
コード例 #17
0
def GetRawPic(list, font_name, font_size, path):
    #get the font
    font = ImageFont.FreeTypeFont(font_name, font_size)
    #drawing
    for char in list:
        img = Image.new('RGB', (2 * font_size, 2 * font_size), (255, 255, 255))
        draw = ImageDraw.Draw(img)
        draw.text((0, 0), char, (0), font=font)
        img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2GRAY)
        # img = get_edges(img)
        cv2.imwrite(path + '/' + char + '.png', img)
    print('done!')
コード例 #18
0
ファイル: cal.py プロジェクト: nta-byte/fontsize-calculation
def get_font_size2(text,
                   wid,
                   height,
                   font_path=None,
                   fontsize=6,
                   jumpsize=7,
                   img_fraction=.3):
    if not font_path:
        font_path = "DejaVuSans.ttf"
    photo = Image.new("1", (wid, height))
    break_point = img_fraction * photo.size[0]
    font_ = ImageFont.FreeTypeFont(font_path, fontsize)
    while True:
        if font_.getlength(text) < break_point:
            fontsize += jumpsize
        else:
            jumpsize = int(jumpsize / 2)
            fontsize -= jumpsize
        font_ = ImageFont.FreeTypeFont(font_path, fontsize)
        if jumpsize <= 1:
            break
    fontsize = int(fontsize / img_fraction)
    return fontsize
コード例 #19
0
def get_font(name: Optional[str] = None,
             size: Optional[int] = None) -> AnyFontType:
    if name is not None and name not in _font_cache:
        raise ValueError(f'No font named "{name}"')

    font: AnyFontType = _font_cache[name] if name is not None else _default_font

    if size is not None:
        if isinstance(font, Font):
            return font.with_size(size)
        elif isinstance(font, ImageFont.FreeTypeFont):
            return ImageFont.FreeTypeFont(font=font.font, size=font.size)

    return font
コード例 #20
0
ファイル: fonts.py プロジェクト: shikhir-arora/Gisi
 def add(self, name, font_io):
     try:
         ImageFont.FreeTypeFont(font_io)
     except OSError:
         raise ValueError("Provided font doesn't seem to be a font!")
     f_name = name.lower().replace(" ", "_")
     if f_name in self.fonts:
         raise ValueError(
             f"A font with this name already exists ({f_name})")
     location = f"{FileLocations.FONTS}/{f_name}.otf"
     font_io.seek(0)
     with open(location, "w+b") as f:
         f.write(font_io.read())
     font = Font(name, location)
     self.fonts[f_name] = font
コード例 #21
0
ファイル: logo.py プロジェクト: pombredanne/biopsy
def get_font(font_name, font_size):
    """
    Tries to load the named font at the given size but falls back on default font if this is not possible.

    @return: The named font at the given size if possible.
    """
    try:
        return ImageFont.truetype(font_name, font_size)
    except:
        #print sys.exc_info()
        warnings.warn('Could not load font from %s of size %d; Trying free type font.' % (font_name, font_size))
        try:
            return ImageFont.FreeTypeFont(font_name, font_size)
        except:
            #print sys.exc_info()
            warnings.warn('Could not load free type font from %s of size %d; Trying default font.' % (font_name, font_size))
        return ImageFont.load_default()
コード例 #22
0
def addBadgeOnPicture(profilePicture, num):
    # Create badge image.
    badge = Image.new('RGBA', (20, 20), (0, 0, 0, 0))
    draw_table = ImageDraw.Draw(im=badge)
    draw_table.text(xy=(0, 0),
                    text=num,
                    fill='red',
                    font=ImageFont.FreeTypeFont(
                        '/System/Library/Fonts/Avenir.ttc', size=20))
    # badge.show()

    # Add badge on profile picture.
    profilePicture = Image.open(profilePicture)
    badgedPicture = profilePicture.copy()
    width, height = badgedPicture.size
    badgedPicture.paste(badge, (width - 10, 5), badge)
    badgedPicture.show()
    badgedPicture.save('result.png')
コード例 #23
0
ファイル: cah_config.py プロジェクト: ttocsneb/cahGenerator
    def renderAndSave(self, dpi: float = 160, relative: str = ""):
        """
        Render and Save all black and white cards
        """
        relfont = os.path.join(
            relative, self.font) if not os.path.isabs(self.font) else self.font
        rel = os.path.join(
            relative, self.out) if not os.path.isabs(self.out) else self.out

        font = ImageFont.FreeTypeFont(relfont, round(FONT_SIZE * dpi))

        if not self.collate:
            xy = tuple(round(i * dpi) for i in DIMENSIONS)
            textW = round(TEXT_WIDTH * dpi)

            self.black.renderAndSave(xy, textW, font, rel, relative=relative)
            self.white.renderAndSave(xy, textW, font, rel, relative=relative)
        else:
            self.black.collate(dpi, font, rel, relative=relative)
            self.white.collate(dpi, font, rel, relative=relative)
コード例 #24
0
def tagErrorImage(location, failimg=None, camname=None):
    """
    Given the failure image filename, add a timestamp to it
    starting at the specified pixel location (lower left corner of text).

    Leaving this hardcoded for now since it is something that's probably
    deployment dependent, but it could be abstracted with work/effort.

    Will save the resulting image to location when it's done.

    TODO: CHANGE THE HARDCODED COORDINATES IN HERE!
    """
    # This is in the package resources directory specified in the package!
    fontfile = "resources/fonts/GlacialIndifference-Bold.otf"

    ff = pkgr.resource_filename('nightshift', fontfile)
    font = ImageFont.FreeTypeFont(ff, size=24, encoding='unic')

    timestamp = dt.utcnow()
    timestring = timestamp.strftime("%Y-%m-%d %H:%M:%S UTC")

    if failimg is None:
        failimgloc = "resources/images/percy_txt.jpg"
        failimg = pkgr.resource_filename('nightshift', failimgloc)

    img = Image.open(failimg)
    dtxt = ImageDraw.Draw(img)

    # We don't actually need the height since I eyeballed it
    tw, _ = font.getsize(timestring)
    ntw = 170 - tw//2

    dtxt.text((ntw, 200), timestring, fill=(255, 76, 76), font=font)

    if camname is not None:
        # Same as above
        tw, _ = font.getsize(camname)
        ntw = 170 - tw//2
        dtxt.text((ntw, 85), camname, fill=(255, 76, 76), font=font)

    img.save(location)
コード例 #25
0
def main():
    img = Image.new('RGB', (ITERATIONS * SCALING, NODES * SCALING + 20),
                    color='black')

    rbn = RandomBooleanNetwork(node_count=NODES,
                               neighbor_count=NODE_NEIGHBOR_COUNT,
                               seed=None)
    rbn.setup()

    draw = ImageDraw.Draw(img)

    for i in range(ITERATIONS):
        for j, node in enumerate(rbn.nodes):
            if node.state == 1:
                rect = (
                    i * SCALING,  # x1
                    j * SCALING,  # y1
                    i * SCALING + SCALING,  # x2
                    j * SCALING + SCALING  # y2
                )
                draw.rectangle(rect,
                               fill='red',
                               outline='red' if SCALING == 1 else 'black')

        rbn.iterate()

    fnt = ImageFont.FreeTypeFont(font='fonts/Roboto/Roboto-Regular.ttf',
                                 size=FONT_SIZE)
    draw.text(xy=(1, NODES * SCALING - 1),
              text=f'S: {rbn.seed}',
              fill='red',
              font=fnt)
    draw.text(
        xy=(1, NODES * SCALING + FONT_SIZE - 1),
        text=f'I: {ITERATIONS} - N: {rbn.node_count} - P: {rbn.neighbor_count}',
        fill='red',
        font=fnt,
        align='right')
    img.save('rbn.png')
コード例 #26
0
    def convert(self, text, output_dir="dataset", fill=(0, 0, 0)):
        """
        convert text to image

        input:
            - text[str]: text object you want convert to image
            - output_dir[str]: output path of images and texts
            - fill[tuple]: background color (r, g, b) each 0-255

        output:
            None
        """
        if not self.font:
            print("Please set ttf with set_font method. Try again.")
            sys.exit(0)
        if not os.path.exists(output_dir):
            os.mkdir(output_dir)
        text_length = len(text)
        size = (50, int(390 * (text_length / 15)), 3)  # decided experimentally
        img = np.zeros(size, dtype=np.uint8)
        if os.path.splitext(self.font)[1].replace(".", "") in ["ttf", "woff"]:
            font = ImageFont.truetype(self.font, 32)
        else:
            font = ImageFont.FreeTypeFont(self.font, 32)
        img_pil = Image.fromarray(img)
        img_pil = ImageOps.invert(img_pil)
        draw = ImageDraw.Draw(img_pil)
        draw.text((20, 10), text, font=font, fill=fill)
        img_pil = self.resizer(img_pil)
        img_pil = self.rotator(img_pil)
        img = np.array(img_pil)
        img_num = len(glob.glob(os.path.join(output_dir, "*.png")))
        font_name = os.path.basename(self.font).split(".")[0]
        output_name = "{}_{}".format(font_name, img_num)
        cv.imwrite(os.path.join(output_dir, output_name + ".png"), img)
        with open(os.path.join(output_dir, output_name + ".txt"), "w") as f:
            f.write(text)
コード例 #27
0
def _textify(x, p=0.9):
    val = np.random.random_sample()

    if np.random.random_sample() < p:
        pil_img = PIL.Image.fromarray(image2np(x * 255).astype(np.uint8))

        w, h = pil_img.size
        text_loc = (random.randint(0, w // 2), random.randint(0, h // 2))
        text_color = (random.randint(0, 255), random.randint(0, 255),
                      random.randint(0, 255))
        text_length = random.randint(1, 10)
        create_string = lambda: random.sample(string.printable, 1)[
            0] + random.sample(string.ascii_letters, 1)[0]
        text = ''.join([create_string() for i in range(text_length)])
        text_size = random.randint(3, 30)
        font = ImageFont.FreeTypeFont("../fonts/arial.ttf", size=text_size)
        ImageDraw.Draw(pil_img).text(text_loc,
                                     text,
                                     fill=text_color,
                                     font=font)

        x = pil2tensor(pil_img, np.float32)
        x.div_(255)
    return x
コード例 #28
0
ファイル: TextFrameItem.py プロジェクト: darthinvader/datavid
 def __init__(self,
              font_path,
              text="",
              x=0,
              y=0,
              current_frame=0,
              frame_added=None,
              font_size=10,
              fill_color=(255, 255, 255, 255),
              spacing=0,
              align="center",
              direction="ltr",
              frames_to_live=-1):
     super().__init__(x, y, current_frame, frame_added, frames_to_live)
     self.text = text
     self.font_size = font_size
     if font_path[-3:] == 'ttf':
         self.font = ImageFont.truetype(font_path, self.font_size)
     elif font_path[-3:] == 'otf':
         self.font = ImageFont.FreeTypeFont(font_path, self.font_size)
     self.fill_color = fill_color
     self.spacing = spacing
     self.align = align
     self.direction = direction
コード例 #29
0
    def _tag_images(self, list_of_pics):
        day_zero = self.time
        # day_zero = "2019:10:27 04:20:00"
        zero_object = datetime.strptime(day_zero, '%Y:%m:%d %H:%M:%S')
        for i in range(len(list_of_pics)):
            p = list_of_pics[i]
            try:
                date_string = (p.getexif()[306])
                date_object = datetime.strptime(date_string,
                                                '%Y:%m:%d %H:%M:%S')

                td = date_object - zero_object
                dif = td / timedelta(days=1)
                # print (dif)
                days = int(dif)
                dif_hours = (dif - days) * 24
                hours = int(dif_hours)
                dif_minutes = (dif_hours - hours) * 60
                minutes = int(dif_minutes)

                dif_text = "{0} days {1} hours and {2} minutes".format(
                    days, abs(hours), abs(minutes))
                if days < 0:
                    dif_text = "T" + dif_text
            except Exception as e:
                dif_text = "No time info found"
                print(e)

            exif = {
                PIL.ExifTags.TAGS[k]: v
                for k, v in p._getexif().items() if k in PIL.ExifTags.TAGS
            }
            try:
                o = (exif['Orientation'])
                if o == 6:
                    list_of_pics[i] = p.rotate(-90)

            except:
                print('No known orientation')

            w = exif['ExifImageWidth']
            h = exif['ExifImageHeight']
            x = int(w * .15)
            y = int(h * .83)

            draw = ImageDraw.Draw(list_of_pics[i])

            text_size = 0
            fs = 0

            while text_size < (w * .7):
                font = ImageFont.FreeTypeFont(font=self.font_path, size=fs)
                text_size = draw.textsize(dif_text, font)[0]
                fs += 1
            # print (fs-1)
            draw.text((x - 1, y - 1), dif_text, (0, 0, 0), font=font)
            draw.text((x + 1, y - 1), dif_text, (0, 0, 0), font=font)
            draw.text((x - 1, y + 1), dif_text, (0, 0, 0), font=font)
            draw.text((x + 1, y + 1), dif_text, (0, 0, 0), font=font)
            draw.text((x, y), dif_text, (255, 255, 0), font=font)
        self.images = list_of_pics
        return list_of_pics
コード例 #30
0
W, H = 640, 360
x = 0

# Gets the current directory
dir_path = os.path.dirname(os.path.realpath(__file__))

# Color defs.
norm = (0, 0, 255)
lower = (153, 153, 0)
higher = (255, 10, 10)
black = (25, 0, 0)
white = (255, 255, 255)

# Font information
fontname = "/usr/share/fonts/truetype/freefont/FreeMono.ttf"
font = ImageFont.FreeTypeFont(fontname, 38)

staff_notes_high = [
    'B6', 'A6', 'G6', 'F6', 'E6', 'D6', 'C6', 'B5', 'A5', 'G5', 'F5', 'E5',
    'D5', 'C5', 'B4', 'A4', 'G4', 'F4', 'E4', 'D4', 'C4'
]
staff_notes_low = [
    'B3', 'A3', 'G3', 'F3', 'E3', 'D3', 'C3', 'B2', 'A2', 'G2', 'F2', 'E2',
    'D2', 'C2', 'B1', 'A1', 'G1', 'F1', 'E1', 'D1', 'C1'
]


class video(object):
    # Local vars.
    frame, errors, modifier = 0, 0, 0
    last_pop_frame, last_pop_frame_time = 0, 0