예제 #1
0
def draw_skeleton(img, coords, joint_mask=None):
    '''Draw a pose skeleton connecting joints (for visualisation purposes).

    Left-hand-side joints are connected with blue lines. Right-hand-size joints
    are connected with red lines. Center joints are connected with magenta
    lines.

    Args:
        img (PIL.Image.Image): PIL image which the skeleton will be drawn over.
        coords (Tensor): 16x2 tensor containing 0-based pixel coordinates
            of joint locations. Joints indices are expected to match
            http://human-pose.mpi-inf.mpg.de/#download
        joint_mask (Tensor, optional): Mask of valid joints (invalid joints
            will be drawn with grey lines).
    '''

    draw = Draw(img)
    for bone_name, (j1, j2) in BONES.items():
        if bone_name.startswith('center_'):
            colour = (255, 0, 255) # Magenta
        elif bone_name.startswith('left_'):
            colour = (0, 0, 255) # Blue
        elif bone_name.startswith('right_'):
            colour = (255, 0, 0) # Red
        else:
            colour = (255, 255, 255)

        if joint_mask is not None:
            # Change colour to grey if either vertex is not masked in
            if joint_mask[j1] == 0 or joint_mask[j2] == 0:
                colour = (100, 100, 100)

        draw.line([coords[j1, 0], coords[j1, 1], coords[j2, 0], coords[j2, 1]], fill=colour)
예제 #2
0
  def _create_noise_curves(self, image, color, width_min=1, width_max=4, n_min=7, n_max=10):
    draw = Draw(image)
    w, h = image.size
    n = np.random.randint(n_min, n_max)
    for _ in range(n):
      A = np.random.randint(0, h / 2)
      f = 1 / np.random.randint(1, 20)
      A *= 0.1

      x = np.arange(0, w, 1)
      size = np.random.randint(w * 0.2, 0.8 * w)
      x = x[:size]
      x += np.random.randint(0, w)
      y = A * np.sin(2*np.pi*f*x)
      y += np.random.randint(0, h / 2)
      points = np.array([x, y]).T

      # Random rotation
      degree = np.random.randint(0, 360)
      radian = np.deg2rad(degree)
      points = rotate_points(points.T, radian, origin=points.mean(axis=0))
      points = points.T
      points = [tuple(p) for p in points]

      width = np.random.randint(width_min, width_max)
      draw.line(points, width=width, fill=color)
    return image
예제 #3
0
def processLine(arr, data):
    blank = Image.new('RGB', (len(arr[0]), len(arr)), color=(0, 0, 0))
    drawer = Draw(blank, 'RGBA')
    for i in range(0, len(data[0])):
        procLine = []
        lx = data[0][i]
        ly = data[1][i]
        for j in range(len(lx)):
            procLine.append((lx[j], ly[j]))
        drawer.line(procLine, fill=(255, 255, 255, 25), width=5)
    blank = blank.convert('L')
    arr = np.asarray(blank)
    # plt.title("Line Map")
    # plt.imshow(arr, cmap='binary', interpolation='nearest')
    # plt.colorbar()
    # plt.show()
    # for i in range(0,np.amax(arr)+10):
    # 	if i in arr:
    # 		print('i = ' + str(i) + ' is in arr')
    # 	else:
    # 		print('i = ' + str(i) + ' is not in arr')

    # print ("LEN: " + str(arr.shape))
    # print("Max 2: " + str( np.amax(arr)))
    return arr
예제 #4
0
 def create_noise_dots(image, color, width=3, number=30):
     draw = Draw(image)
     w, h = image.size
     while number:
         x1 = random.randint(0, w)
         y1 = random.randint(0, h)
         draw.line(((x1, y1), (x1 - 1, y1 - 1)), fill=color, width=width)
         number -= 1
     return image
예제 #5
0
파일: image.py 프로젝트: aiguy110/captcha
 def create_noise_dots(image, color, width=3, number=30):
     draw = Draw(image)
     w, h = image.size
     while number:
         x1 = random.randint(0, w)
         y1 = random.randint(0, h)
         draw.line(((x1, y1), (x1 - 1, y1 - 1)), fill=color, width=width)
         number -= 1
     return image
예제 #6
0
 def noise(self, number=62, level=2, color=None):
     """绘制扰码"""
     width, height = self._image.size
     dx, dy = width / 10, height / 10
     width, height = width - dx, height - dy
     draw = Draw(self._image)
     for i in range(number):
         x = int(random.uniform(dx, width))
         y = int(random.uniform(dy, height))
         draw.line(((x, y), (x + level, y)), fill=color if color else self._color, width=level)
예제 #7
0
 def drawer(image_, text_):
     width, height = image_.size
     dx = width / 10
     width = width - dx
     dy = height / 10
     height = height - dy
     draw = Draw(image_)
     for i in range(number):
         x = int(random.uniform(dx, width))
         y = int(random.uniform(dy, height))
         draw.line(((x, y), (x + level, y)), fill=color(), width=level)
     return image_
예제 #8
0
 def noise(self, image, number=50, level=2, color=None):
     width, height = image.size
     dx = width / 10
     width -= dx
     dy = height / 10
     height -= dy
     draw = Draw(image)
     for i in range(number):
         x = int(random.uniform(dx, width))
         y = int(random.uniform(dy, height))
         draw.line(((x, y), (x + level, y)), fill=color if color else self._color, width=level)
     return image
예제 #9
0
 def drawer(image, text):
     width, height = image.size
     dx = width / 10
     width = width - dx
     dy = height / 10
     height = height - dy
     draw = Draw(image)
     for i in xrange(number):
         x = int(random.uniform(dx, width))
         y = int(random.uniform(dy, height))
         draw.line(((x, y), (x + level, y)), fill=color(), width=level)
     return image
예제 #10
0
 def noise(self, image, number=50, level=2, color=None):
     width, height = image.size
     dx = width / 10
     width -= dx
     dy = height / 10
     height -= dy
     draw = Draw(image)
     for i in xrange(number):
         x = int(random.uniform(dx, width))
         y = int(random.uniform(dy, height))
         draw.line(((x, y), (x + level, y)), fill=color if color else self._color, width=level)
     return image
예제 #11
0
def draw_arrow(draw_obj: ImageDraw.Draw,
               start: Tuple[int, int],
               end: Tuple[int, int],
               mustache_length: int = 10,
               width: int = 2,
               color: Tuple[int, int, int] = (0, 0, 255)) -> ImageDraw.Draw:
    draw_obj.line([start, end],  fill=color, width=width)
    # draw_obj.line([
    #     (end[0] + (mustache_length * math.cos(ANGLE)), (end[1] + mustache_length * math.sin(ANGLE))),
    #     end,
    #     ((end[0] - mustache_length * math.cos(ANGLE)), (end[1] + mustache_length * math.sin(ANGLE))),
    # ],  fill=color, width=width)
    return draw_obj
예제 #12
0
 def drawer(image, text):
     dx, height = image.size
     dx = dx / number
     path = [(dx * i, random.randint(0, height))
             for i in range(1, number)]
     bcoefs = make_bezier(number - 1)
     points = []
     for coefs in bcoefs:
         points.append(tuple(sum([coef * p for coef, p in zip(coefs, ps)])
                       for ps in zip(*path)))
     draw = Draw(image)
     draw.line(points, fill=color(), width=width)
     return image
예제 #13
0
def draw_compiled(img, xyc_it, thickness=1):
    """Draws a sequence of x,y,color tuples onto an image.

    xyc_it: iterator of x,y,color tuples. The color of the first entry is
        discarded, all other colors are used as the respective line's color"""
    center_x, center_y = map(lambda n: n / 2, img.size)
    d = Draw(img, "RGBA")
    (x, y), _ = next(xyc_it)
    x, y = x * img.scale + center_x, y * img.scale + center_y
    for ((x2, y2), c) in xyc_it:
        x2, y2 = x2 * img.scale + center_x, y2 * img.scale + center_y
        d.line((x, y, x2, y2), c, width=thickness)
        x, y = x2, y2
예제 #14
0
 def create_noise_dots(image,
                       color,
                       width=random.randint(1, 5),
                       number=random.randint(2, 60)):
     draw = Draw(image)
     w, h = image.size
     if random.random() > 0.5:
         return image
     while number:
         x1 = random.randint(0, w)
         y1 = random.randint(0, h)
         draw.line(((x1, y1), (x1 - 1, y1 - 1)), fill=color, width=width)
         number -= 1
     return image
예제 #15
0
 def drawer(image_, text_):
     dx, height = image_.size
     dx = dx / number
     path = [(dx * i, random.randint(0, height)) for i in range(1, number)]
     bcoefs = make_bezier(number - 1)
     points = []
     for coefs in bcoefs:
         points.append(
             tuple(
                 sum([coef * p for coef, p in zip(coefs, ps)])
                 for ps in zip(*path)))
     draw = Draw(image_)
     draw.line(points, fill=color(), width=width)
     return image_
예제 #16
0
 def getSagittalImage(self, ml, ap, dv, show=True):
     """
     Return an image of the Sagittal slice at this corrdinate and where in
     the image does the specified coordinate lie.
     """
     url_data = self.queryServer(ml, ap, dv)
     self.sagittal_image = fetchImage(url_data['sagittal']['image_url'])
     coordinates = (url_data['sagittal']['left'],
                    url_data['sagittal']['top'])
     if show:
         placement = Draw(self.sagittal_image)
         # placement.line([(coordinates[0], IMAGE_TOP), coordinates], fill=(0, 0, 225), width=LINE_WIDTH)
         placement.line([(coordinates[0], IMAGE_TOP), coordinates], fill=0)
         self.sagittal_image.show()
     return (self.sagittal_image, coordinates)
예제 #17
0
def drawLine(im, coords, **kwargs):
    # May or may not be taken care of by kwargs
    if not ('drawIm' in kwargs): drawIm = kwargs['drawIm']
    else: drawIm = Draw(im)

    if ('fillColor' in kwargs): fillColor = kwargs['fillColor']
    else: fillColor = 'blue'

    polyArr = []
    for j in range(len(coords[0])):
        polyArr.append(coords[0][j])
        polyArr.append(coords[1][j])

    drawIm.line(polyArr, fill=fillColor, width=5)
    return im
예제 #18
0
 def show_single(self, draw: ImageDraw.Draw, last_sample: Sample,
                 top_line: int) -> None:
     probe = self.PROBES[self.page]
     width, ypos = self.fonts[1].heading.getsize(probe.name)
     xpos = (self.width - width) // 2
     draw.text(((xpos, top_line)),
               probe.name,
               fill=probe.colour,
               font=self.fonts[1].heading)
     value = self.value_str(probe, last_sample.values[self.page])
     width, height = self.fonts[1].body.getsize(value)
     xpos = self.width - width
     ypos += 2 + top_line
     draw.text(((xpos, ypos)),
               value,
               fill=probe.colour,
               font=self.fonts[1].body)
     ypos += height + 2
     num_samples = len(self.samples)
     if num_samples < 3:
         return
     if num_samples < self.width:
         points = [s.values[self.page] for s in self.samples]
     else:
         scale = num_samples // self.width
         points: List[float] = []
         for i in range(0, num_samples, scale):
             pts = [s.values[self.page] for s in self.samples[i:i + scale]]
             points.append(float(sum(pts)) / len(pts))
     step = max(1, self.width / float(len(points)))
     min_val = min(points) * 0.9
     max_val = max(points) * 1.1
     draw.text((0, ypos), '{0:3.0F}'.format(max_val), fill='yellow')
     draw.text((0, self.height - 12),
               '{0:3.0F}'.format(min_val),
               fill='cyan')
     xpos = 0
     yscale = (self.height - ypos) / float(max(1, max_val - min_val))
     coords = []
     for pt in points:
         ypos = self.height - (pt - min_val) * yscale
         coords.append((xpos, ypos))
         xpos += step
     draw.line(coords, fill='white')
     if min_val < 0 and max_val >= 0:
         ypos = self.height + min_val * yscale
         draw.line(((0, ypos), (self.width, ypos)), fill='#777')
예제 #19
0
 def getCoronalImage(self, ml, ap, dv, show=True):
     """
     Return an image of the Coronal slice at this corrdinate and where in
     the image does the specified coordinate lie.
     """
     url_data = self.queryServer(ml, ap, dv)
     self.coronal_image = fetchImage(
         url_data['coronal']['image_url']).convert('RGB')
     coordinates = (url_data['coronal']['left'], url_data['coronal']['top'])
     if show:
         placement = Draw(self.coronal_image)
         placement.line([(coordinates[0], IMAGE_TOP), coordinates],
                        fill=(255, 0, 0),
                        width=LINE_WIDTH)
         # TODO: Coloring breaks the drawing
         # placement.line([(coordinates[0], IMAGE_TOP), coordinates])
         self.coronal_image.show(title="%2.2fum" % dv)
     return (self.coronal_image, coordinates)
예제 #20
0
def gradient(color):
    size_x = 512
    size_y = 200

    new_color = (0, 0, 0)
    new_image = Image.new('RGB', (size_x, size_y), new_color)
    draw = Draw(new_image)
    for i in range(256):
        if color.upper() == 'R':
            draw_line = draw.line((i*2, 0, i*2, 200), fill=(i, 0, 0), width=2)
        elif color.upper() == 'G':
            draw_line = draw.line((i * 2, 0, i * 2, 200), fill=(0, i, 0), width=2)
        elif color.upper() == 'B':
            draw_line = draw.line((i * 2, 0, i * 2, 200), fill=(0, 0, i), width=2)
        else:
            print('Please, choose on of these colors: red(R), green(G) or blue(B).')

    # new_image.show()
    new_image.save('image.png', 'PNG')
예제 #21
0
파일: schedule.py 프로젝트: zane-deg/accent
    def empty_timeline(self):
        """Generates an empty timeline image."""

        image = Image.new(mode='RGB',
                          size=(TIMELINE_WIDTH, TIMELINE_HEIGHT),
                          color=TIMELINE_BACKGROUND)
        draw = Draw(image)

        # Draw each day of the week.
        num_days = len(day_abbr)
        for day_index in range(num_days):
            x = TIMELINE_DRAW_WIDTH * day_index / num_days

            # Draw a dashed vertical line.
            for y in range(0, TIMELINE_HEIGHT, 2 * TIMELINE_LINE_DASH):
                draw.line([(x, y), (x, y + TIMELINE_LINE_DASH - 1)],
                          fill=TIMELINE_FOREGROUND,
                          width=TIMELINE_LINE_WIDTH)

            # Draw the abbreviated day name.
            name = day_abbr[day_index]
            day_x = x + TIMELINE_DRAW_WIDTH / num_days / 2
            day_y = TIMELINE_HEIGHT - SCREENSTAR_SMALL_REGULAR['height']
            draw_text(name,
                      SCREENSTAR_SMALL_REGULAR,
                      TIMELINE_FOREGROUND,
                      xy=(day_x, day_y),
                      anchor=None,
                      box_color=None,
                      box_padding=0,
                      border_color=None,
                      border_width=0,
                      image=image,
                      draw=draw)

        # Draw another dashed line at the end.
        for y in range(0, TIMELINE_HEIGHT, 2 * TIMELINE_LINE_DASH):
            draw.line([(TIMELINE_DRAW_WIDTH, y),
                       (TIMELINE_DRAW_WIDTH, y + TIMELINE_LINE_DASH - 1)],
                      fill=TIMELINE_FOREGROUND,
                      width=TIMELINE_LINE_WIDTH)

        return image
예제 #22
0
def generate_capture(request):
    """
    You can visit the view with GET params like k, b, f to custom the capture.
    b indicates background color, and f foreground color.
    The value of color should be an integer, which will be convert to a hex color value. That is to say the value
     of a color should not be less than 0 or larger than 16777215.
    k indicates the key of the capture. It should exist in session before this view is visited, otherwise A 404 error
    will be throw out.
    And once the view is visited, the answer of the capture will be set a key in session which k indicates.
    """
    keyName, bcolor, fcolor = DEFAULT_CAPTURE_ID, DEFAULT_BACKGROUND, DEFAULT_FOREGROUND
    if 'k' in request.GET:
        if request.GET['k'] in request.session:
            keyName = request.GET['k']
        else:
            raise Http404()
    try:
        if 'b' in request.GET:
            bcolor = '#{:0>6.6s}'.format('%x' % max(min(int(request.GET['b']), 16777215), 0))
        if 'f' in request.GET:
            fcolor = '#{:0>6.6s}'.format('%x' % max(min(int(request.GET['f']), 16777215), 0))
    except:
        raise Http404()
    ver_fun = snippets[randint(0, len(snippets) - 1)]
    x, y = ver_fun[2](), ver_fun[3]()
    request.session[keyName] = '%r' % ver_fun[1](x, y)
    img = Image.new("RGB", (DEFAULT_WIDTH, DEFAULT_HEIGHT), bcolor)
    draw = Draw(img)
    font = ImageFont.truetype('font/SourceCodePro-Regular.ttf', DEFAULT_FONT_SIZE)
    for i in xrange(0, 3):
        draw.line([(0, randint(0, DEFAULT_HEIGHT)), (DEFAULT_WIDTH, randint(1, DEFAULT_HEIGHT))],
                  fill='#{:0>6.6s}'.format('%x' % randint(0, 16777215)))
    if x < 0:
        x = '(%s)' % x
    if y < 0:
        y = '(%s)' % y
    text = ver_fun[0] % (x, y)
    x, y = font.getsize(text)
    draw.text((DEFAULT_WIDTH / 2 - x / 2, DEFAULT_HEIGHT / 2 - y / 2), text, font=font, fill=fcolor)
    response = HttpResponse(mimetype='image/png')
    img.save(response, 'PNG')
    return response
예제 #23
0
파일: captcha.py 프로젝트: jeanbon/pycoblog
def generate_captcha(directory="tmp", letters=ascii_uppercase+digits,
        length=3, font_size=30, lines=5, mode="ellipse", font="FreeSerif.ttf"):
    """ Returns a tuple : (path, code) """
    dimensions = ((length + 1) * font_size, int(font_size * 2))
    path = "%s%s" % (os.path.join(directory, "".join(choice(ascii_letters) for
        i in xrange(7))), ".png")
    code = "".join(choice(letters) for i in range(length))
    background_color = tuple( [randrange(190, 230) for i in xrange(3)] )
    master = new_image("RGB", dimensions, background_color)

    # On colle les lettres
    for i, l in enumerate(code):
        img, mask = generate_letter(l, font_size, font)
        for _ in xrange(3):
            # On colle plusieurs fois pour plus de netteté
            master.paste(img, (font_size / 2 + font_size * i , font_size / 3),
                    mask)

    # Et on dessine quelques jolies lignes
    draw = Draw(master)
    for i in xrange(lines):
        color = tuple( [randrange(128, 190) for i in xrange(3)] )
        #pen = Pen("black", opacity=64)
        #pen.color = color
        w = dimensions[0]
        h = dimensions[1]
        geom = (randrange(0, int(w * 3. / 4)), randrange(0, h),
                randrange(int(w * 1. / 4), w), randrange(0, h))
        if mode == "mixed":
            mode_ = choice( ("ellipse", "line") )
        else:
            mode_ = mode
        if mode_ == "ellipse":
            draw.ellipse(geom, None, color)
        else:
            draw.line(geom, color, 1)
    with open(path, "w") as f:
        master.save(f)
    return (path, code)
예제 #24
0
파일: revis.py 프로젝트: frietz58/se_hiob
 def create_image(self):
     im = Image.new("RGB", self.size, "white")
     draw = Draw(im)
     # add horizontal lines to show limits:
     for v in self.ylines:
         ry = 1 - (v - self.min_y) / (self.max_y - self.min_y)
         ry = ry * self.size[1]
         draw.line(((0, ry), (self.size[0], ry)), "green", 1)
     # draw values as connected dotes to create a graph
     last_pos = None
     for n, v in enumerate(self.store):
         if v is None:
             last_pos = None
             continue
         ry = 1 - (v - self.min_y) / (self.max_y - self.min_y)
         pos = (n, ry * self.size[1])
         if last_pos is None:
             draw.point(pos, "black")
         else:
             draw.line([last_pos, pos], "black", 1)
         last_pos = pos
     self.image = im
     self.dirty = False
예제 #25
0
    def draw_grid(image, background, line_width=4):
        w, h = image.size
        line_color = background

        # draw grid
        x_start = 0
        x_end = w
        y_start = 0
        y_end = h

        step_width_size = int(w / random.randint(5, 8))
        step_height_size = int(h / random.randint(3, 5))

        draw = Draw(image)

        for x in range(0, w, step_width_size):
            xy = ((x, y_start), (x, y_end))
            draw.line(xy, fill=line_color, width=line_width)

        for y in range(0, h, step_height_size):
            xy = ((x_start, y), (x_end, y))
            draw.line(xy, fill=line_color, width=line_width)

        return image
예제 #26
0
    def draw_grid(image, line_width=4):
        w, h = image.size
        line_color = (255, 255, 255)

        # draw grid
        x_start = 0
        x_end = w
        y_start = 0
        y_end = h

        step_width_size = int(w / 7)
        step_height_size = int(h / 4)

        draw = Draw(image)

        for x in range(0, w, step_width_size):
            xy = ((x, y_start), (x, y_end))
            draw.line(xy, fill=line_color, width=line_width)

        for y in range(0, h, step_height_size):
            xy = ((x_start, y), (x_end, y))
            draw.line(xy, fill=line_color, width=line_width)

        return image
예제 #27
0
 def draw_lines(draw: ImageDraw.Draw, x, y):
     line_col = DARKEST_GRAY
     a = (x, y)
     b = (x + 30, y)
     c = (x, y + 30)
     d = (x + 30, y + 30)
     e = (x + 10, y)
     f = (x + 20, y)
     g = (x, y + 10)
     h = (x + 30, y + 10)
     i = (x, y + 20)
     j = (x + 30, y + 20)
     k = (x + 10, y + 30)
     l = (x + 20, y + 30)
     draw.line((*a, *b), line_col, width=1)
     draw.line((*a, *c), line_col, width=1)
     draw.line((*b, *d), line_col, width=1)
     draw.line((*c, *d), line_col, width=1)
     draw.line((*e, *k), line_col, width=1)
     draw.line((*f, *l), line_col, width=1)
     draw.line((*g, *h), line_col, width=1)
     draw.line((*i, *j), line_col, width=1)
예제 #28
0
    def paint(self, draw: ImageDraw.Draw, regions: RegionMap) -> None:
        angle = radians(180.0 - 30)  # 30 degrees
        c, s = cos(angle), sin(angle)
        d = self.p1[0] - self.p0[0], self.p1[1] - self.p0[1]
        left = d[0] * c - d[1] * s, d[0] * s + d[1] * c
        right = d[0] * c + d[1] * s, -d[0] * s + d[1] * c
        lf = self.size / (d[0]**2 + d[1]**2)**0.5

        # Draw arrow shaft
        draw.line([self.p0, self.p1], fill=self.color, width=self.width)
        # Draw dot
        draw.ellipse(
            (self.p1[0] - 5, self.p1[1] - 5, self.p1[0] + 5, self.p1[1] + 5),
            fill=self.color)
        # Draw left arrow wing
        draw.line(
            [(self.p1[0] + lf * left[0], self.p1[1] + lf * left[1]), self.p1],
            fill=self.color,
            width=self.width)
        # Draw right arrow wing
        draw.line([(self.p1[0] + lf * right[0], self.p1[1] + lf * right[1]),
                   self.p1],
                  fill=self.color,
                  width=self.width)
overlay_path = output_directory + 'overlay/'

make_sure_path_exists(overlay_path)

# Superimpose smoothed midlines on the (cropped) original image sequence
for i in range(Nf):
    shift = -offsets[i]
#    im = Image.open(original_images.format(i+1))
#    im = im.crop((0, 680, 2260, 680+810)) 
    im = open_png(sillhouette_path.format(i+1))
    im = Image.fromarray(im.astype(np.uint8)).convert('RGB')
    d = Draw(im)
    y = smid[:,i].astype(int)+shift[1]
    x = (np.arange(smid.shape[0])*end[i]/float(smid.shape[0]-1)).astype(int)+shift[0]
    d.line(zip(x,y), fill=(255,0,0), width=3 )
    tp = tip_locations[i]
    d.ellipse((tp[0]-1, tp[1]-1, tp[0]+1, tp[1]+1), fill=(0,0,255))
    im.save(overlay_path+'orig_{}.png'.format(i))


# Calculate scaling between transformed and y-coordinate
# in pixels - dy/di
sc = end / float(smid.shape[0]-1)

# Evaluate derivatives of the smoothed midline - dx/dy and d^2 x / dy^2
# Use scaling factor to give in terms of pixel coordinates
d = u(range(new_mid.shape[0]), range(new_mid.shape[1]), dx=1)/sc
dd = u(range(new_mid.shape[0]), range(new_mid.shape[1]), dx=2)/sc/sc

예제 #30
0
class LsystemImage(object):
    def __init__(self,
                 lsystem: Lsystem,
                 size: tuple = (0, 0),
                 start_coords: tuple = (0, 0),
                 start_angle: float = 0,
                 rot_angle: float = 0,
                 step_length: int = 1,
                 bg_color="#000000",
                 line_color="#FFFFFF") -> None:
        self.lsystem = lsystem
        self.size = size
        self.start_coords = start_coords
        self.start_angle = start_angle
        self.rot_angle = rot_angle
        self.step_length = step_length
        self.bg_color = bg_color
        self.line_color = line_color

    def _make_empty_image(self) -> None:
        self.image = Image.new("RGBA", self.size, self.bg_color)

    def _make_draw(self) -> None:
        self.draw = Draw(self.image)

    def _draw_lsystem(self) -> None:
        not_drawn_lines = 0
        x, y = self.start_coords[0], self.start_coords[1]
        angle = self.start_angle
        stack = []
        for char in self.string:
            if char == "F":
                new_x, new_y = point_on_circle((x, y), self.step_length, angle)
                if check_coords((x, y), (new_x, new_y), self.size):
                    self.draw.line(((x, y), (new_x, new_y)),
                                   fill=self.line_color,
                                   width=1)
                    not_drawn_lines = 0
                else:
                    not_drawn_lines += 1
                x, y = new_x, new_y
            elif char == "f":
                x, y = point_on_circle((x, y), self.step_length, angle)
            elif char == "+":
                angle -= self.rot_angle
            elif char == "-":
                angle += self.rot_angle
            elif char == "|":
                angle += pi
            elif char == "[":
                stack.append((x, y, angle))
            elif char == "]":
                x, y, angle = stack.pop()
            if not_drawn_lines >= 30000:
                break

    def get_image(self) -> Image:
        return self.image

    def update_image(self, iteration: int) -> None:
        self.string = self.lsystem.generate_string(iteration)
        self._make_empty_image()
        self._make_draw()
        self._draw_lsystem()

    def set_size(self, size: tuple) -> None:
        self.size = size

    def set_size(self, heigth: int, width: int) -> None:
        self.size = (heigth, width)

    def set_start_coords(self, coords: tuple) -> None:
        self.start_coords = coords

    def set_start_coords(self, x: int, y: int) -> None:
        self.start_coords = (x, y)

    def set_start_angle(self, angle: float) -> None:
        self.start_angle = angle

    def set_rot_angle(self, angle: float) -> None:
        self.rot_angle = angle

    def set_step_length(self, length: int) -> None:
        self.step_length = length

    def set_bg_color(self, color) -> None:
        self.bg_color = color

    def set_line_color(self, color) -> None:
        self.line_color = color

    def get_size(self) -> tuple:
        return self.size
예제 #31
0
def visualize_hog(hog_features, img):
    dim_width  = img.shape[1]
    dim_height = img.shape[0]

    zoom = 3
    img = Image.fromarray(img)

    cell_size = 8
    bin_size  = 9
    rad_range = 180 / 9

    nb_width  = dim_width // cell_size
    nb_height = dim_height // cell_size

    gradients_strength = [[[.0 for _ in range(bin_size)]
                           for _ in range(nb_width)]
                          for _ in range(nb_height)]

    cell_update_counter = [[0 for _ in range(nb_width)]
                           for _ in range(nb_height)]

    hog_index = 0

    for block_w in range(nb_width - 1):
        for block_h in range(nb_height - 1):
            for cell in range(4):
                cell_w = block_w
                cell_h = block_h
                if cell == 1:
                    cell_h += 1
                elif cell == 2:
                    cell_w += 1
                elif cell == 3:
                    cell_w += 1
                    cell_h += 1

                for b in range(bin_size):
                    gradient_strength = hog_features[hog_index]
                    hog_index += 1
                    gradients_strength[cell_h][cell_w][b] += gradient_strength

                cell_update_counter[cell_h][cell_w] += 1


    for cell_w in range(nb_width):
        for cell_h in range(nb_height):
            nb_update = cell_update_counter[cell_h][cell_w]

            for b in range(bin_size):
                gradients_strength[cell_h][cell_w][b] /= nb_update


    draw = Draw(img)
    for cell_w in range(nb_width):
        for cell_h in range(nb_height):
            draw_x = cell_w * cell_size
            draw_y = cell_h * cell_size

            my_x = draw_x + cell_size / 2
            my_y = draw_y + cell_size / 2

            """
            draw.rectangle([(draw_x, draw_y),
                            (draw_x+cell_size, draw_y+cell_size)],
                           outline=128)
            """

            for b in range(bin_size):
                grad = gradients_strength[cell_h][cell_w][b]
                if grad == 0:
                    continue

                rad = b * rad_range + rad_range/2
                rad_x = math.cos(rad)
                rad_y = math.sin(rad)
                max_vec_len = cell_size/2
                scale = 2.5

                x0 = my_x - rad_x * grad * max_vec_len * scale
                y0 = my_y - rad_y * grad * max_vec_len * scale
                x1 = my_x + rad_x * grad * max_vec_len * scale
                y1 = my_y + rad_y * grad * max_vec_len * scale

                draw.line([(x0, y0), (x1, y1)], fill="red")

    img = img.resize((128, 256))
    return img
예제 #32
0
 def draw_dot(image, color, width=2):
     w, h = image.size
     draw = Draw(image)
     x1 = random.randint(0, w)
     y1 = random.randint(0, h)
     draw.line((x1, y1, x1 - 1, y1 - 1), fill=color, width=width)
예제 #33
0
 def paint(self, draw: ImageDraw.Draw, regions: RegionMap) -> None:
     xy = list(map(tuple, self.linestring.coords))
     draw.line(xy, self.color, self.width)
예제 #34
0
def connect_dots(draw: ImageDraw.Draw, coords):
    for c1, c2 in zip(coords, coords[1:]):
        draw.line((c1, c2), "red", 2)
예제 #35
0
def draw_bounding_box_on_image(image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               color='red',
                               thickness=4,
                               display_str_list=(),
                               use_normalized_coordinates=True):
    print(
        'DRAWING BOX***********************************************************************************'
    )
    # convert to Pillow image
    print('Converting image to Pillow img')
    image_pillow = fromarray(image)

    print('Instantiated Draw object with input image')
    draw = Draw(image_pillow)

    print('Grabbing image dimensions')
    im_width, im_height = image_pillow.size

    if use_normalized_coordinates:
        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                      ymin * im_height, ymax * im_height)
    else:
        (left, right, top, bottom) = (xmin, xmax, ymin, ymax)

    print('Drawing line')
    draw.line([(left, top), (left, bottom), (right, bottom), (right, top),
               (left, top)],
              width=thickness,
              fill=color)

    print('Setting font')
    try:
        font = truetype('arial.ttf', 24)
    except IOError:
        font = load_default()

    print('Calculating possible boundary exceed')
    # If the total height of the display strings added to the top of the bounding
    # box exceeds the top of the image, stack the strings below the bounding box
    # instead of above.
    display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]
    # Each display_str has a top and bottom margin of 0.05x.
    total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)

    if top > total_display_str_height:
        text_bottom = top
    else:
        text_bottom = bottom + total_display_str_height
    # Reverse list and print from bottom to top.
    for display_str in display_str_list[::-1]:
        text_width, text_height = font.getsize(display_str)
        margin = ceil(0.05 * text_height)
        draw.rectangle([(left, text_bottom - text_height - 2 * margin),
                        (left + text_width, text_bottom)],
                       fill=color)
        draw.text((left + margin, text_bottom - text_height - margin),
                  display_str,
                  fill='black',
                  font=font)
        text_bottom -= text_height - 2 * margin
    # overwrite original image with (Pillow -> numpy array) image
    copyto(image, array(image_pillow))

    return image
예제 #36
0
파일: schedule.py 프로젝트: knyar/accent
    def timeline(self, user):
        """Generate a timeline image of the schedule for settings."""
        image = self.empty_timeline()
        draw = Draw(image)

        # Find the user or return the empty timeline.
        try:
            now = self._local_time.now(user)
        except DataError as e:
            return image

        # Start the timeline with the most recent beginning of the week.
        start = now.replace(hour=0, minute=0, second=0)
        start -= timedelta(days=start.weekday())
        stop = start + timedelta(weeks=1)
        start_timestamp = datetime.timestamp(start)
        stop_timestamp = datetime.timestamp(stop)
        timestamp_span = stop_timestamp - start_timestamp

        # Draw a dashed line in highlight color at the current time.
        now_timestamp = datetime.timestamp(now)
        now_x = TIMELINE_DRAW_WIDTH * (now_timestamp -
                                       start_timestamp) / timestamp_span
        for y in range(0, TIMELINE_HEIGHT, 2 * TIMELINE_LINE_DASH):
            draw.line([(now_x, y), (now_x, y + TIMELINE_LINE_DASH - 1)],
                      fill=TIMELINE_HIGHLIGHT,
                      width=TIMELINE_LINE_WIDTH)

        # Generate the schedule throughout the week.
        entries = user.get('schedule')
        if not entries:
            # Empty timeline.
            return image
        for i in range(len(entries)):
            entries[i]['index'] = i
        time = start
        while time < stop:
            # Find the next entry.
            next_entries = [(self._next(entry['start'], time,
                                        user), entry['index'], entry)
                            for entry in entries]
            next_datetime, next_index, next_entry = min(next_entries,
                                                        key=lambda x: x[0])

            # Draw the entry's index and a vertical line, with a tilde to mark
            # the variable sunrise and sunset times.
            timestamp = datetime.timestamp(next_datetime)
            x = TIMELINE_DRAW_WIDTH * (timestamp -
                                       start_timestamp) / timestamp_span
            y = TIMELINE_HEIGHT / 2
            text = str(next_index + 1)
            next_entry_start = next_entry['start']
            if 'sunrise' in next_entry_start or 'sunset' in next_entry_start:
                text = '~' + text
            box = draw_text(text,
                            SCREENSTAR_SMALL_REGULAR,
                            TIMELINE_FOREGROUND,
                            xy=(x, y),
                            anchor=None,
                            box_color=None,
                            box_padding=4,
                            border_color=None,
                            border_width=0,
                            image=image,
                            draw=draw)
            draw.line([(x, 0), (x, box[1])], fill=TIMELINE_FOREGROUND, width=1)

            # Jump to the next entry.
            time = next_datetime

        return image
예제 #37
0
from PIL import Image
from PIL.ImageDraw import Draw
img = Image.new("RGBA", (100, 100))
draw = Draw(img)
draw.rectangle(((0,0), (100, 100)), fill=(255, 100, 0))
draw.rectangle((50,80,100,200), fill=0)
# img.save("foo.png")
imshow(numpy.asarray(img))

# <codecell>

given_image_size = (600, 900)
image_min_dimen = min(given_image_size)
image_center = (given_image_size[0] / 2, given_image_size[1] / 2)

from PIL import Image
from PIL.ImageDraw import Draw
from math import sin, cos, radians
import random
img = Image.new("RGBA", given_image_size)
draw = Draw(img)
span = 3600
for i in range(0, span):
    deg = float(i) / span * 360
    draw.line((image_center[0], image_center[1], image_center[0] + sin(radians(deg)) * image_min_dimen * 0.4 , image_center[1] + cos(radians(deg)) * image_min_dimen * 0.4), fill=(0, 0, 0), width=2)
imshow(numpy.asarray(img))

# <codecell>


예제 #38
0
# If the picture is part of the bounding box dataset, use the golden value.
p2bb = {}
for i,(p,coords) in enumerate(data): p2bb[p] = bounding_rectangle(coords)
len(p2bb)
# For other pictures, evaluate the model.
p2bb = {}
for p in tqdm_notebook(join):
    if p not in p2bb:
        img,trans         = read_for_validation(p)
        a                 = np.expand_dims(img, axis=0)
        x0, y0, x1, y1    = model2.predict(a).squeeze()
        (u0, v0),(u1, v1) = coord_transform([(x0,y0),(x1,y1)], trans)
        p2bb[p]           = (u0, v0, u1, v1)
import pickle

with open('bounding-box.pickle', 'wb') as f: pickle.dump(p2bb, f)
samples = []
for p in tagged[:25]:
    img         = read_raw_image(p).convert('RGB')
    draw        = Draw(img)
    x0,y0,x1,y1 = p2bb[p]
    draw.line([(x0, y0),(x0,y1),(x1,y1),(x1,y0),(x0,y0)], fill='yellow', width=6)
    samples.append(img)
show_whale(samples)
import os

os.remove('cropping-1.h5')
os.remove('cropping-2.h5')
os.remove('cropping-3.h5')
### ls *.pickle *.model
예제 #39
0
        color.append(int(s))
        color2.append(int(s2))

    color = tuple(color2)
    w, h = 426, 240
    image = Image.new("RGB", (w, h), (0, 0, 0))
    draw = Draw(image)
    text = name if True else ", ".join([f"{c:.2f}" for c in cc])
    ww, hh = draw.textsize(text)
    draw.text(((w - ww) // 2, (h - hh) // 2), text)
    line = [0, h]
    for ii, tone in enumerate(range(12)):
        line.append(int((ii + 1) * w / 13))
        line.append(h - 50 * cc[tone])
    line += [w, h]
    draw.line(line, width=1, fill=color)
    image.save(f"imgs/img{i:09}.png")

    for o in range(height):
        overview.putpixel((i, o), color)

plt.figure(figsize=(10, 6))

plt.subplot(2, 1, 1)
plt.imshow(np.asarray(overview), interpolation='nearest', aspect='auto')
plt.title('Color')

plt.subplot(2, 1, 2)
librosa.display.specshow(C,
                         sr=sr,
                         hop_length=hop_length,