def score_hour_lines(draw: ImageDraw): for hour in range(HOURS): y = hour * HOUR_HEIGHT draw.line(( (0, y), (NUM_DAYS * DAY_WIDTH, y), ), fill='grey')
def _render(self, draw: ImageDraw.ImageDraw, image: Image.Image): rect = (self._position[0], self._position[1], self._position[0] + self._width, self._position[1] + self._height) # Border draw.rectangle(rect, fill=0, outline=1) # Fill p_range = abs(self._min_value) + abs(self._max_value) zero_pct = (0 + abs(self._min_value)) / p_range zero_pt = (self._position[0] + 2 + (zero_pct * (self._width - 4)), self._position[1] + 2) val_pct = self._value / (self._max_value - self._min_value) fill_rect = (zero_pt[0], zero_pt[1], zero_pt[0] + (val_pct * (self._width - 4)), zero_pt[1] + self._height - 4) draw.rectangle(fill_rect, fill=1) # Draw Zero Indicator draw.line((zero_pt[0], zero_pt[1] - 1, zero_pt[0], zero_pt[1] + self._height - 2), fill=255, width=1) # Draw Intervals if self._interval > 0: for i in range(0, self._max_value + 1, self._interval): itv_pct = i / p_range itv_pos = (zero_pt[0] + (itv_pct * (self._width - 4)), zero_pt[1] + (self._height / 2)) draw.line((itv_pos[0], itv_pos[1], itv_pos[0], zero_pt[1] + self._height - 3), fill=255, width=1) for i in range(0, self._min_value - 1, -self._interval): itv_pct = i / p_range itv_pos = (zero_pt[0] + (itv_pct * (self._width - 4)), zero_pt[1] + (self._height / 2)) draw.line((itv_pos[0], itv_pos[1], itv_pos[0], zero_pt[1] + self._height - 3), fill=255, width=1)
def generate_image(self, num_digits=30, noise=None): if noise: a = np.array(np.random.random_integers(0, 64, (self._height, self._width)), dtype=np.uint8) else: a = np.zeros((self._height, self._width), dtype=np.uint8) im = Image.frombytes('L', (self._width, self._height), a.tobytes()) canvas = ImageDraw(im) for i in range(num_digits): import random x = random.randint(0, self._width - self._char_size) y = random.randint(0, self._height - self._char_size) class_index = random.randint(0, self._num_classes - 1) ch = str(class_index) character_bitmap = self._factory.get_digit_image(ch) character_bitmap = character_bitmap.resize( (self._char_size, self._char_size) ) canvas.bitmap((x, y), character_bitmap, fill=255) return im
def _render(self, draw: ImageDraw.ImageDraw, image: Image.Image): rect = (self._position[0], self._position[1], self._position[0] + self._width, self._position[1] + self._height) draw.rectangle(rect, fill=255 if self._filled else 0, outline=self._bordered)
def word_wrap(text: str, draw: ImageDraw.ImageDraw, width: int) -> str: text_width, text_height = draw.multiline_textsize(text, font=font) if text_width > width: lines = text.splitlines() wrapped_text = [] for line in lines: line_width, _ = draw.textsize(line, font=font) if line_width > width: new_line = '' last_line = new_line for word in line.split(): if len(new_line) > 0: new_line += ' ' new_line += word line_width, _ = draw.textsize(new_line, font=font) if line_width > width: wrapped_text.append(last_line) new_line = word last_line = new_line if len(last_line) > 0: wrapped_text.append(last_line) else: wrapped_text.append(line) return '\n'.join(wrapped_text) else: return text
def line(draw: ImageDraw, coord1: Coordinate, coord2: Coordinate): """Draws a line between two given Coordinates. The color of the line depends on the Y value (low = black, high = white) Arguments: draw {ImageDraw} -- The ImageDraw to draw on coord1 {Coordinate} -- Coordinate of the original position coord2 {Coordinate} -- Coordinate of the next position """ # R G B # low black: 0 0 0 # high white: 225 225 255 # Limit elevation to be between 70 and 120 ll = 70.0 ul = 120.0 pos1 = coord1.coord_3d pos2 = coord2.coord_3d elev = max(ll, min(pos1[1], ul)) # The RGB tuple to make the gray for the given elevation gray = (int(scale(elev, (ll, ul), (0.0, 255.0))), ) * 3 draw.line([(pos1[0], pos1[2]), (pos2[0], pos2[2])], gray, 4)
def color_pix(color): im = new_im('RGB', (128, 128)) draw = ImageDraw(im, 'RGB') draw.rectangle((0, 0, 128, 128), fill=(int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16))) return toqpixmap(im)
def do_I_have_to_draw_you_a_picture(self): """ Return a little thumbs-up / thumbs-down image with text in it. """ if self.success: bytes, color = _thumbs_up_bytes, _thumbs_up_color else: bytes, color = _thumbs_down_bytes, _thumbs_down_color thumb = Image.open(StringIO(bytes)) image = Image.new('RGB', (256, 256), color) image.paste(thumb.resize((128, 128)), (64, 80)) mapnik_url = 'http://tile.openstreetmap.org/%(zoom)d/%(column)d/%(row)d.png' % self.coord.__dict__ mapnik_img = Image.open(StringIO(urlopen(mapnik_url).read())) mapnik_img = mapnik_img.convert('L').convert('RGB') image = Image.blend(image, mapnik_img, .15) draw = ImageDraw(image) margin, leading = 8, 12 x, y = margin, margin for word in self.content.split(): w, h = draw.textsize(word) if x > margin and x + w > 250: x, y = margin, y + leading draw.text((x, y), word, fill=(0x33, 0x33, 0x33)) x += draw.textsize(word + ' ')[0] return image
def draw_eye_vector(drawer: ImageDraw.ImageDraw, eye_3d_vector: np.ndarray, solver: PNP_solver.PoseEstimator, rotation: np.ndarray, translation: np.ndarray, eye_pos: str) -> None: """Draw gaze vector eye from eye on a picture drawer :param drawer: where to draw :param eye_3d_vector: what vector(in camera coordinate system) :param solver: :param rotation: head rotation :param translation: head translation :param eye_pos: "l" for left, "r" for right :return: """ if eye_pos == "l": eye_pos = (solver.model_points_68[36] + solver.model_points_68[39]) / 2. else: eye_pos = (solver.model_points_68[42] + solver.model_points_68[45]) / 2. eye_3d_vector = copy.deepcopy(eye_3d_vector) * -50 # eye coordinate in camera coordinate system is determined to_camera_matrix = get_world_to_camera_projection_matrix(solver, rotation, translation) eye_pos = np.matmul(to_camera_matrix, [*eye_pos, 1]) no_rot_vector, _ = cv2.Rodrigues(np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])) vect_start, _ = cv2.projectPoints(eye_pos, no_rot_vector, [0, 0, 0], solver.camera_matrix, solver.dist_coeefs) vect_finish, _ = cv2.projectPoints(eye_3d_vector + eye_pos, no_rot_vector, [0, 0, 0], solver.camera_matrix, solver.dist_coeefs) drawer.line([*vect_start, vect_start[0] + vect_finish[0], vect_start[1] + vect_finish[1]], fill=(0, 255, 0)) drawer.ellipse([vect_start[0] - 2, vect_start[1] - 2, vect_start[0] + 2, vect_start[1] + 2])
def verification_code(request): """ :param request: :return: about:生成4位随机验证码图 """ mode = 'RGB' size = (100, 34) color_bg = (get_bg_color(), get_bg_color(), get_bg_color()) # 画布 image = Image.new(mode=mode, size=size, color=color_bg) # 画笔 image_draw = ImageDraw(image, mode=mode) image_font = ImageFont.truetype(settings.FONT_PATH, random.randrange(30, 34)) # 绘制文字 code = get_code() request.session['verification_code'] = code for i in range(4): fill = (get_color(), get_color(), get_color()) image_draw.text(xy=(i * random.randrange(18, 28), random.randrange(5)), text=code[i], font=image_font, fill=fill) for i in range(2): fill = (get_color(), get_color(), get_color()) xy1 = ((random.randrange(100), random.randrange(50)), (random.randrange(75), random.randrange(25))) image_draw.line(xy=xy1, fill=fill) xy2 = ((random.randrange(50), random.randrange(100)), (random.randrange(34), random.randrange(13))) image_draw.line(xy=xy2, fill=fill) for i in range(10): fill = (get_color(), get_color(), get_color()) xy1 = ((random.randrange(100), random.randrange(50)), (random.randrange(75), random.randrange(25))) image_draw.point(xy=xy1, fill=fill) # 变成比特流 fp = BytesIO() image.save(fp, 'png') return HttpResponse(fp.getvalue(), content_type='image/png')
def add_polygon_to_image(draw: ImageDraw.ImageDraw, poly_points: list, scale: float, line_color: str, fill_color: str = None) -> None: """Draw a polygon on an image This will draw a polygon on the passed-in image in the specified colors and scale. :param draw: The drawable surface to write on :param poly_points: A sequence of points representing the polygon, where each point has float members (x, y) :param scale: Scale to multiply each point to match the image scaling :param line_color: The color for the outline of the polygon. The string value must be a color string suitable for use with PIL - see :mod:`PIL.ImageColor` :param fill_color: The color for the inside of the polygon. The string value must be a color string suitable for use with PIL - see :mod:`PIL.ImageColor` """ if len(poly_points) < 2: # Need at least 2 points to draw any lines return # Convert poly_points to the PIL format and scale them to the image pil_poly_points = [] for pt in poly_points: pil_poly_points.append((pt.x * scale, pt.y * scale)) draw.polygon(pil_poly_points, fill=fill_color, outline=line_color)
def getcode(request): mode = 'RGB' size = [200, 100] color_bg = getcolor() image = Image.new(mode=mode, size=size, color=color_bg) imagedraw = ImageDraw(image, mode=mode) iamgefont = ImageFont.truetype(settings.FONT_PATH, 30) verify_code = 'Come' for i in range(len(verify_code)): # file text填充色 fill = getcolor() imagedraw.text(xy=(30 * i, 30), text=verify_code[i], font=iamgefont, fill=fill) # 干扰点 for i in range(1000): xy = (random.randrange(size[0]), random.randrange(size[1])) fill = getcolor() imagedraw.point(xy=xy, fill=fill) # 画圆 xy区域,四元数组 start int end int 圆经过strat和end start = random.randrange(size[0]) end = random.randrange(size[1]) fill = getcolor() imagedraw.arc(xy=(0, 0, 200, 100), start=start, end=end, fill=fill) for i in range(10): imagedraw.line(xy=( random.randrange(size[0]), random.randrange(size[1]), (random.randrange(size[0]), random.randrange(size[1]))), fill=getcolor()) fp = BytesIO() image.save(fp, 'png') cache.set('code', verify_code) return HttpResponse(fp.getvalue(), content_type='image/png')
def add_img_box_to_image( draw: ImageDraw.ImageDraw, box: util.ImageRect, color: str, text: Union[ImageText, Iterable[ImageText]] = None) -> None: """Draw a box on an image and optionally add text. This will draw the outline of a rectangle to the passed in image in the specified color and optionally add one or more pieces of text along the inside edge of the rectangle. :param draw: The drawable surface to write on :param box: The ImageBox defining the rectangle to draw :param color: A color string suitable for use with PIL - see :mod:`PIL.ImageColor` :param text: The text to display - may be a single ImageText instance, or any iterable (eg a list of ImageText instances) to display multiple pieces of text. """ x1, y1 = box.x_top_left, box.y_top_left x2, y2 = (box.x_top_left + box.width), (box.y_top_left + box.height) draw.rectangle([x1, y1, x2, y2], outline=color) if text is not None: if isinstance(text, collections.Iterable): for t in text: t.render(draw, (x1, y1, x2, y2)) else: text.render(draw, (x1, y1, x2, y2))
def __draw_header_without_profile_pic( tweet_info: TweetInfo, graphic_settings: GraphicSettings, wip_img: Image.Image, draw_interface: ImageDraw.ImageDraw, coordinates: Tuple[int], header_height: int, font_header: ImageFont.FreeTypeFont, ) -> int: """Draw the graphic's header: username and user tag only. Parameters ---------- tweet_info : TweetInfo Dictionary with all the tweet's information. graphic_settings : GraphicSettings Dictionary with the graphic's settings. wip_img : Image.Image Work-in-progress tweet graphic. draw_interface : ImageDraw.ImageDraw Interface used to draw in the Image. coordinates : Tuple[int] Initial coordinates at which to draw the header. header_height : int Total height of the header. font_header : ImageFont.FreeTypeFont Font used for the header. profile_picture : Image.Image Profile picture ready to be drawn in the graphic. Returns ------- int Vertical coordinate at which to start drawing the tweet body. """ x = coordinates[0] y = coordinates[1] username = tweet_info["user_name"] user_name = wrap(username, 19) user_tag = tweet_info["user_tag"] text_color = graphic_settings["color_scheme"][1] margin = graphic_settings["margin_bottom"] profile_pic_width = graphic_settings["profile_pic_size"][0] # Draw the username user_name = wrap(username, 38) for line in user_name: draw_interface.text((x, y), line, font=font_header, fill=text_color) y += font_header.size + margin # Draw the user tag draw_interface.text((x, y), user_tag, font=font_header, fill=text_color) # Calculate the vertical coordinate at which to start drawing the\ # tweet text return_y = coordinates[1] + header_height + margin # Return the current vertical coordinate return return_y
def build_monster(seed=None, size=None): #capture random state rand_state = random.getstate() if not seed: seed = md5(str(random.getrandbits(128))).hexdigest() random.seed(seed) parts = ( ('legs', random.randint(0, 4), random.randint(1, 5)), ('hair', random.randint(0, 4), random.randint(1, 5)), ('arms', random.randint(0, 4), random.randint(1, 5)), ('body', random.randint(0, 4), random.randint(1, 15)), ('eyes', random.randint(0, 4), random.randint(1, 15)), ('mouth', random.randint(0, 4), random.randint(1, 10)), ) #restore random state random.setstate(rand_state) # make a base monster: monster_im = Image.new('RGB', (120, 120)) monster_id = ImageDraw(monster_im) monster_id.rectangle((0, 0, 120, 120), fill="white", outline="white") for part, flip, index in parts: f = path(__file__).dirname().abspath() / 'parts' / '%s_%d.png' % (part, index) part_im = Image.open(f) monster_im.paste(part_im, (0, 0), part_im) if size: monster_im = monster_im.resize(size, Image.ANTIALIAS) return monster_im
def _draw_num(self, num: int, draw: ImageDraw, x_offset: float = 0, y_offset: float = 0): for points in self.num_points(num, x_offset, y_offset): draw.polygon(points, fill=self.fg)
def _render_label_box( self, draw: ImageDraw.ImageDraw, top_left: Tuple[int, int], text: str, padding: int = 10, background_color: Tuple[int, int, int] = (255, 255, 255), outline_color: Tuple[int, int, int] = (0, 0, 0), text_color: Tuple[int, int, int] = (0, 0, 0), ): text_size = draw.textsize(text, font=self.font) offset_x, offset_y = self.font.getoffset(text) text_width = text_size[0] + offset_x text_height = text_size[1] + offset_y x, y = top_left bottom_right = ( x + self.border * 2 + padding * 2 + text_width, y + padding + text_height, ) box_coords = [top_left, bottom_right] draw.rectangle( box_coords, fill=background_color, outline=outline_color, width=self.border, ) text_coordinate = ( x + self.border + padding - offset_x, y + self.border + padding - offset_y + 1, ) draw.text(text_coordinate, text, font=self.font, fill=text_color)
def makeCircleMaskImage(width, height): center = (width / 2, height / 2) smallerDimension = min(width, height) image = Image.new('1', (width, height)) draw = ImageDraw(image) draw.ellipse(boundingBoxSquare(center, smallerDimension), fill='white') return image
def draw_title( draw: ImageDraw.ImageDraw, title_font: ImageFont.FreeTypeFont, title: str, sub_title: Optional[str] = None, sub_title_font: Optional[ImageFont.FreeTypeFont] = None) -> None: size_width, size_height = draw.textsize(title, title_font) x_padding = 20 y_padding = 4 draw.rectangle(((0, 0), (size_width + x_padding, size_height + y_padding)), fill=0x00) draw.text(((size_width + x_padding) // 2, (size_height + y_padding) // 2), title, fill="white", font=title_font, anchor='mm') if (sub_title): if (not sub_title_font): sub_title_font = title_font sub_title_size_width, _ = draw.textsize(sub_title, sub_title_font) draw.rectangle(((size_width + x_padding, 0), (size_width + x_padding + sub_title_size_width + 40, size_height + y_padding)), fill=0xff, outline=0, width=4) draw.text(((size_width + x_padding + (sub_title_size_width + 40) // 2), (size_height + y_padding) // 2), sub_title, fill="black", font=sub_title_font, anchor='mm')
def run(self): # no need to overwrite parent's init turtle = self.turtle colors = self.colors if self.load_from_cache(): return self.canvas.begin_new() im_draw = ImageDraw(self.canvas.pil_image) color = self.colors["1"] # Calculate size, and scale to fill the frame t_width = turtle.rightmost[0] - turtle.leftmost[0] t_height = turtle.bottommost[1] - turtle.topmost[1] if t_width / t_height > 1: # fat image scale according to width scale_factor = self.canvas.c_width / t_width else: scale_factor = self.canvas.c_height / t_height left_margin = (self.canvas.c_width - scale_factor * t_width) / 2 top_margin = (self.canvas.c_height - scale_factor * t_height) / 2 x_shift = left_margin - scale_factor * turtle.leftmost[0] y_shift = top_margin - scale_factor * turtle.topmost[1] coordinates = [] for item in turtle.lines: if self._stop_drawing.isSet(): return if isinstance(item, PlaceHolder): coordinates.append(item) else: coordinates.append((item[0] * scale_factor + x_shift, item[1] * scale_factor + y_shift, item[2] * scale_factor + x_shift, item[3] * scale_factor + y_shift)) i = 0 for item in coordinates: if self._stop_drawing.isSet(): return "Update canvas after each 3000 stroke" i += 1 if i > 3000: self.canvas.update_image() i = 0 if isinstance(item, PlaceHolder): # not a list of coordinates if item.value in colors: color = colors[item.value] else: im_draw.line(item, color) self.canvas.update_image() self.save_to_cache()
def draw_route_frame(self, route: list, frame: int, draw: ImageDraw.ImageDraw) -> None: """Draws single frame of route for single player.""" first_pos = (self.gran * int((route[frame]['x_pos']) + 20), self.gran * int(route[frame]['y_pos'])) second_pos = (self.gran * int((route[frame + 1]['x_pos']) + 20), self.gran * int(route[frame + 1]['y_pos'])) draw.line((first_pos, second_pos), fill=255, width=self.gran*1)
def draw_line(draw: ImageDraw.ImageDraw, target, offset=(0, 0), scale=1.0): vertexes = [] for vertex in target['vertexes']: x = vertex['x'] * scale + offset[0] y = vertex['y'] * scale + offset[1] vertexes.append((int(x), int(y))) # draw draw.line(vertexes)
def plot_square(self, route_start: dict, draw: ImageDraw.ImageDraw) -> None: """Plots square to signify player at start of route.""" x_pos, y_pos = route_start['x_pos'], route_start['y_pos'] draw.rectangle((self.gran * (int(x_pos) + self.gran * 10 - 1), self.gran * (int(y_pos) + 1), self.gran * (int(x_pos) + self.gran * 10 + 1), self.gran * (int(y_pos) - 1)), fill=255)
def draw(self, features: List, osm_helper: OsmHelper, camera: Camera, image_draw: ImageDraw): for point, text in sorted(features, key=itemgetter(1)): x, y = camera.gps_to_px(point) width, height = image_draw.textsize(text, font=self.font) image_draw.text((x - width // 2, y - height // 2), text=text, fill=self.fill, font=self.font)
def fill_rainbows(image, angle=0): draw_api = ImageDraw(image) for col in range(IMG_SIZE): hue = (col * MAX_HUE / IMG_SIZE + angle) % MAX_HUE colour_string = "hsl(%d, 100%%, 50%%)" % (hue) # logging.warning("colour_string: %s" % colour_string) rgb = ImageColor.getrgb(colour_string) # logging.warning("rgb: %s" % (rgb,)) draw_api.line([(col, 0), (col, IMG_SIZE)], fill=rgb)
def draw_linestring(image, linestring, color=255): """Draw a linestring in the given color at the given location""" pil_image = fromarray(image) validated_color = color draw = ImageDraw(pil_image) if len(image.shape) > 2 and image.shape[2] > 1: validated_color = tuple(color) draw.line(linestring.coords, fill=validated_color) return np.asarray(pil_image)
def draw_poly(image, polygon, color=255): """Draw a polygon in the given color at the given location""" pil_image = fromarray(image) validated_color = color draw = ImageDraw(pil_image) if len(image.shape) > 2 and image.shape[2] > 1: validated_color = tuple(color) draw.polygon(polygon.boundary.coords, fill=validated_color, outline=validated_color) return np.asarray(pil_image)
def draw_username( txt_draw: ImageDraw.ImageDraw, position: Point, username="******", fill=TITLE_COLOR, ): x0 = position.x + MSG_PADDING_H y0 = position.y + MSG_PADDING_V txt_draw.text((x0, y0), username, font=FONTS['bold'], fill=fill)
def __init__(self, size=(200, 100), mode='RGB', font_path=settings.FONT_PATH): self.size = size mode = mode bg_color = self.RGB() self.image = Image.new(mode=mode, size=self.size, color=bg_color) self.draw = ImageDraw(self.image, mode) self.font = ImageFont.truetype(font_path, 20) self.code_length = 4 self.code = self.CAPTCHA()
def draw(self, verbose=False): """ Draw map out to a PIL.Image and return it. """ # image and filename img = Image.new('RGB', (self.width, self.height), 0x00) if verbose: print 'Laying out faces...' face = icosahedron.vertex2face(icosahedron.latlon2vertex(self.latitude, self.longitude)) face.orient_north(self.latitude, self.longitude) face.center_on(self.latitude, self.longitude) face.scale(self.side) face.translate(img.size[0]/2, img.size[1]/2) faces = face.arrange_neighbors(self.join) if verbose: print 'Drawing faces...' applied = [] for f, face in icosahedron.faces.items(): if face in faces: applied += apply_face(img, ['%02d' % f], face, UP, verbose=verbose) lock = threading.Lock() pasters = [TilePaster(img, srcPath, affineData, lock, verbose) for (srcPath, affineData) in applied] for paster in pasters: paster.start() while True: time.sleep(.25) remaining = sum(map(int, [paster.isAlive() for paster in pasters])) if remaining == 0: break if verbose: print 'Drawing lines...' draw = ImageDraw(img) for face in faces: for edge in face.edges(): x1, y1 = face.project_vertex(edge.vertexA) x2, y2 = face.project_vertex(edge.vertexB) if edge.kind == icosahedron.LAND: draw.line((x1, y1, x2, y2), fill=(0x00, 0xCC, 0x00, 0x80)) elif edge.kind == icosahedron.WATER: draw.line((x1, y1, x2, y2), fill=(0x00, 0x66, 0xFF, 0x80)) return img
def __generate_copyright_image(self, size): text_layer = Image.new('RGBA', size, (255, 255, 255, 0)) draw_object = ImageDraw(text_layer) opacity = self.count_opacity_num() position = self.count_copyright_text_position(size) draw_object.text(position, self.copyright_text, fill=(255, 255, 255, opacity)) return text_layer
def draw_quantity(draw: ImageDraw.ImageDraw, mid_point: tuple[int, int], value: str, unit: str, fonts: Fonts, font: str = 'font_sm', font_unit: str = 'font_xs') -> None: (x, y) = mid_point draw.text((x - 7, y), value, font=fonts[font], fill=0, anchor='rs') draw.text((x + 7, y), unit, font=fonts[font_unit], fill=0, anchor='ls')
def draw_ant(draw: ImageDraw.ImageDraw, ant: Ant): y, x = ant.position pos = (np.array([x, y]) + .5) * c.C2P rot = rotation(-ant.direction * TAU / 8) start = rot @ np.array([0., -c.C2P / 3]) + pos end = rot @ np.array([0., c.C2P / 3]) + pos color = (255, 0, 0) if ant.food else (0, 0, 0) draw.line(start.tolist() + end.tolist(), fill=color, width=2)
def draw_flag_path(self, image, flag_path): flag_path = flag_path[0] pen = ImageDraw(image) x = 0 while x < len(flag_path) - 1: x1, y1 = flag_path[x] x2, y2 = flag_path[x + 1] pen.line(((x1 * 40) + 20, (y1 * 40) + 20, (x2 * 40) + 20, (y2 * 40) + 20), "yellow", width=4) x += 1
def score_hour_lines(draw: ImageDraw): for hour in range(HOURS): y = hour * HOUR_HEIGHT draw.line( ( (0, y), (NUM_DAYS * DAY_WIDTH, y), ), fill='grey' )
def __init__(self, *args, **kwargs): global src, dst self.g = TPS_generate(src, dst) self.img = Image.new("L", (500, 500), 255) draw = ImageDraw(self.img) for d in xrange(10, 250, 10): draw.ellipse((d, d, 500 - d, 500 - d)) return super(TestImages, self).__init__(*args, **kwargs)
def draw_weekday_names(draw: ImageDraw): for day_num, day_name in enumerate(calendar.day_abbr): draw.text( ( day_num * DAY_WIDTH, (7 * HOUR_HEIGHT) + (HOUR_HEIGHT / 2) ), day_name.upper(), fill='black', font=SOURCE_CODE_PRO )
def create_test_image(w, h, c='RGB'): colors = { 'RGB': {1: '#DDEEFF', 2: '#667788', 3: '#887766'}, 'CMYK': {1: (120, 130, 140, 25), 2: (80, 100, 120, 50), 3: (120, 100, 80, 75)}, } color = colors[c] img = Image.new(c, (w, h), color=color[1]) d = ImageDraw(img) d.line((-1, -1) + img.size, fill=color[2], width=2) d.line((-1, img.size[1], img.size[0], -1), fill=color[3], width=2) return img
def procesar(): sqs = boto3.resource('sqs') queue = sqs.get_queue_by_name(QueueName='designMatchQueue') print 'Queue' print str(queue.url) print 'Entra a procesar' lista_disenios = Connection().db.disenios.find({'estado' : 'En proceso'}) print 'lista_disenios' print lista_disenios for disenio in lista_disenios: disenio = Connection.db.disenios.find_one({'_id' : ObjectId(disenio['_id'])}) if disenio['estado']=='En proceso': Connection().db.disenios.update({"_id": ObjectId(disenio['_id'])}, {"$set": {'fechaInicioProceso': timezone.now(), 'fechaModificacion': timezone.now(), 'estado': 'Procesando'}}) print 'Procesando disenio... ' + str(disenio['disenioOriginal']) imageS3 = default_storage.open(disenio['disenioOriginal']) imagenOrg = Image.open(imageS3) #Redimensionar imagenPro = imagenOrg.resize((800,600),Image.ANTIALIAS) #Marca de agua watermark = Image.new("RGBA", imagenPro.size) waterdraw = ImageDraw(watermark, "RGBA") font = ImageFont.truetype("fonts/DejaVuSans.ttf", 25) waterdraw.text((50,50), disenio['nombres'] + ' ' + disenio['apellidos'] + ' ' + str(disenio['fechaCreacion']), (255,255,255), font=font) watermask = watermark.convert("L").point(lambda x: min(x, 100)) watermark.putalpha(watermask) imagenPro.paste(watermark, None, watermark) #Nueva extension nombreImagen = disenio['disenioOriginal'].split('/')[1].split('.')[0] #time.sleep(90) nuevaRuta = 'diseniosProcesados/' + nombreImagen + '_procesada.png' #Guardar local #imagenPro.save(nuevaRuta) #Guardar en base fh = default_storage.open(nuevaRuta, 'w') imagenPro.save(fh) fh.close() print "Imagen guardada en S3 " + nuevaRuta Connection().db.disenios.update({"_id": ObjectId(disenio['_id'])}, {"$set": {'disenioProcesado': nuevaRuta, 'fechaModificacion': timezone.now(), 'estado': 'Disponible'}}) prompt(disenio)
def render(rgb_from_coords=None, filename="mandelbrot.png"): """ Display an image of dimensions MAX_X, MAX_Y, delegating to rgb_from_coords to choose the colour for the current pixel. :param rgb_from_coords:Function mapping x, y to (r, g, b). """ if rgb_from_coords is None: raise ValueError("Pass in a callback function (x, y)->(r,g,b).") img = Image.new("RGB", (MAX_X, MAX_Y)) draw = ImageDraw(img) t1 = time.time() for coords in it.product(range(MAX_X), range(MAX_Y)): rgb = rgb_from_coords(*coords) draw.point(coords, rgb) t2 = time.time() print("Calculation and rendering took", t2-t1, "seconds in total.") img.save(filename)
def draw_rectangle(colours: dict, class_: TimetableClass, draw: ImageDraw, start: int, stop: int): colour = colours[class_.name.split(' - ')[0]] fill, outline = colour, 'black' draw.rectangle( (start, stop), fill=fill, outline=outline ) colour = tuple(min(x - 20, 256) for x in colour) draw.rectangle( ( start, (stop[0], start[1] + (HOUR_HEIGHT * (2/3))) ), fill=colour, outline=outline )
def draw_label(draw: ImageDraw, start: ('x', 'y'), class_: TimetableClass): unit_name, class_type = class_.name.split(' - ') unit_initials = ''.join( word[:1] for word in unit_name.split() if word[:1].isupper() or word[:1].isdigit() ) start = (start[0] + 2, start[1] - 3) draw.text( start, unit_initials, font=SOURCE_CODE_PRO ) if class_type in CLASS_TYPES: class_type = CLASS_TYPES[class_type] else: class_type = class_type[:3].upper() draw.text( (start[0], start[1] + 20), class_type, font=SOURCE_CODE_PRO )
def do_label(fname): print "Processing %s" % fname # remove directory and file extension label = fname.split('/')[-1].replace(".png", "") img = Image.open(fname) img = img.convert("RGBA") # label draw = ImageDraw(img, "RGBA") font = ImageFont.truetype("arial.ttf", 12) draw.setfont(font) draw.text((6, 6), label, (0, 0, 0, 255)) draw.text((5, 5), label, (255, 255, 255, 255)) # border img2 = Image.new("RGBA", img.size, (0, 0, 0, 0)) draw = ImageDraw(img2, "RGBA") draw.rectangle((0, 0, img.size[0] - 1, img.size[1] - 1), None, (255, 255, 192, 48)) img.paste(img2, img2) img.save(fname)
def run(self): # no need to overwrite parent's init turtle = self.turtle colors = self.colors if self.load_from_cache(): return self.canvas.begin_new() im_draw = ImageDraw(self.canvas.pil_image) color = self.colors["1"] # Calculate size, and scale to fill the frame t_width = turtle.rightmost[0] - turtle.leftmost[0] t_height = turtle.bottommost[1] - turtle.topmost[1] if t_width / t_height > 1: # fat image scale according to width scale_factor = self.canvas.c_width / t_width else: scale_factor = self.canvas.c_height / t_height left_margin = (self.canvas.c_width - scale_factor*t_width) / 2 top_margin = (self.canvas.c_height - scale_factor*t_height) / 2 x_shift = left_margin - scale_factor*turtle.leftmost[0] y_shift = top_margin - scale_factor*turtle.topmost[1] coordinates = [] for item in turtle.lines: if self._stop_drawing.isSet(): return if isinstance(item, PlaceHolder): coordinates.append(item) else: coordinates.append((item[0]*scale_factor+x_shift, item[1]*scale_factor+y_shift, item[2]*scale_factor+x_shift, item[3]*scale_factor+y_shift)) i = 0 for item in coordinates: if self._stop_drawing.isSet(): return "Update canvas after each 3000 stroke" i += 1 if i > 3000: self.canvas.update_image() i = 0 if isinstance(item, PlaceHolder): # not a list of coordinates if item.value in colors: color = colors[item.value] else: im_draw.line(item, color) self.canvas.update_image() self.save_to_cache()
max_z_pos = -sys.maxint - 1 for r_ in blocks: if(r_.x_pos_real > max_x_pos): max_x_pos = r_.x_pos_real elif(r_.x_pos_real < min_x_pos): min_x_pos = r_.x_pos_real if(r_.z_pos_real > max_z_pos): max_z_pos = r_.z_pos_real elif(r_.z_pos_real < min_z_pos): min_z_pos = r_.z_pos_real width = abs(max_z_pos - min_z_pos)+4 height = abs(max_x_pos - min_x_pos)+4 print('width {0}, height {1}'.format(width, height)) img = Image.new("RGB", (width, height), "white") draw = ImageDraw(img) for r_ in blocks: chunk_x = r_.x_pos_chunk chunk_z = r_.z_pos_chunk for x_ in range(16): for z_ in range(16): draw.point((chunk_z + z_ - min_x_pos + 2, chunk_x + x_ - max_x_pos + 2), r_.color) draw.point((r_.x_pos_real - min_x_pos + 2, r_.z_pos_real - min_z_pos + 2), "black") img.save("img.png", "PNG")
def annotate(image, text): draw = ImageDraw(image) font = truetype("Helvetica.otf", 16) draw.text((0, 0), text, (255, 255, 255), font=font)
import dymaxion import PIL.Image as Image from PIL.ImageDraw import ImageDraw min_x, min_y, max_x, max_y = 9999, 9999, -9999, -9999 points = [] img = Image.new("L", (800, 400), 0x00) draw = ImageDraw(img) for lat in range(-90, 90, 3): for lon in range(-180, 180, 3): x, y = dymaxion.project(lon, lat) x, y = x, -y # upside-down! min_x, min_y = min(x, min_x), min(y, min_y) max_x, max_y = max(x, max_x), max(y, max_y) # print (lat, lon), '->', (x, y) points.append((x, y, lat, lon)) print(min_x, min_y), (max_x, max_y) top, left, bottom, right = 10, 10, img.size[1] - 10, img.size[0] - 10 mx = (right - left) / (max_x - min_x) my = (bottom - top) / (max_y - min_y) mx, my = min(mx, my), min(mx, my) bx = left - mx * min_x
def getalbums(**kwargs): items = kwargs.get('items', []) app_id = kwargs.get('app_id', '') app_secret = kwargs.get('app_secret', '') try: oauth = urllib2.urlopen( 'https://graph.facebook.com/oauth/access_token?' 'client_id=%s&client_secret=%s&grant_type=client_credentials' % (app_id, app_secret)) txt = oauth.read() access_token = re.search('access_token=(.*)', txt).groups()[0] except Exception as e: print e sys.exit(0) facebook = hammock.Hammock("https://graph.facebook.com") # 851 315 # 840 300 # 120 100 images = [] for item in items: try: metadata = facebook.__getattr__(item).GET( "", params={"access_token": access_token} ).json() feed = facebook.__getattr__(metadata['id']).GET( "albums", params={"access_token": access_token} ).json() filtered = [ i for i in feed['data'] if not i['name'] in ( u'Profile Pictures', u'Cover Photos', u'Timeline Photos' )] shuffle(filtered) items = [] for album in filtered: photos = facebook.__getattr__(album['id']).GET( "photos", params={"access_token": access_token} ).json() chosen = sample( photos['data'], choice(range(1, int(math.ceil(len(filtered) ** 0.5)))) ) items.extend(chosen) shuffle(items) for c in items: print "processing", c['source'] try: data = StringIO(urllib2.urlopen(c['source']).read()) img = Image.open(data) if choice((0, 1)): img = img.resize(( img.size[0] / 2, img.size[1] / 2), Image.ANTIALIAS) if img.size[0] < img.size[1]: # portrait img = img.crop(( max(img.size[0] / 2 - 120 * choice((1, 2)), 0), max(img.size[1] / 2 - 105 * choice((2, 3)), 0), min(img.size[0] / 2 + 120, img.size[0]), min(img.size[1] / 2 + 105, img.size[1]), )) else: # landscape img = img.crop(( max(img.size[0] / 2 - 120 * choice((2, 3)), 0), max(img.size[1] / 2 - 105 * choice((1, 2)), 0), min(img.size[0] / 2 + 120, img.size[0]), min(img.size[1] / 2 + 105, img.size[1]), )) draw = ImageDraw(img) draw.rectangle( [1, 1, img.size[0] - 2, img.size[1] - 2], outline="white" ) draw.rectangle( [0, 0, img.size[0] - 1, img.size[1] - 1], outline="white" ) images.append( Rectangle( 0, 0, img.size[0], img.size[1], img )) except Exception as e: print e #pass except Exception as e: print e sys.exit(0) container = Rectangle( 0, 0, 1440, 500, Image.open("template.png")) guillotine_baf_las(container, images) depth_composite(container, container, 0, 0) offset = choice(tuple(i for i in range(0, 100, 10))) crop = container.image.crop(( offset, offset, 851 + offset, 315 + offset )) draw = ImageDraw(crop) draw.rectangle( (0, 0, crop.size[0] - 1, crop.size[1] - 1), outline="white" ) draw.rectangle( (1, 1, crop.size[0] - 2, crop.size[1] - 2), outline="white" ) crop.save(open("result.png", "w"))
import dymaxion import os, tempfile, subprocess import PIL.Image as Image from PIL.ImageDraw import ImageDraw as IDraw from PIL.ImageStat import Stat as IStat min_x, min_y, max_x, max_y = 9999, 9999, -9999, -9999 points = [] img = Image.new('RGB', (1440, 900), 0x00) draw = IDraw(img) sources = (('world.topo.bathy.200407.3x21600x21600.A1.v', 'world.topo.bathy.200407.3x21600x21600.B1.v', 'world.topo.bathy.200407.3x21600x21600.C1.v', 'world.topo.bathy.200407.3x21600x21600.D1.v'), ('world.topo.bathy.200407.3x21600x21600.A2.v', 'world.topo.bathy.200407.3x21600x21600.B2.v', 'world.topo.bathy.200407.3x21600x21600.C2.v', 'world.topo.bathy.200407.3x21600x21600.D2.v')) def source(lat, lon): if lat > 0: row = 0 else: row = 1 if lon < -90: col = 0 elif lon < 0: col = 1 elif lon < 90: col = 2 else: col = 3 image = sources[row][col]
def renderTile(self, width, height, srs, coord): """ """ img = Image.new('RGB', (width, height), colors[0]) draw = ImageDraw(img) interactivity_array = [] base_zoom = coord.zoom base_row = coord.row base_column = coord.column #We're showing detail for three zooms in from here, as fat pixels (32 pix) #256 pixels / tile = 8 pixels / tile = 32 pixels (which is 2^5) tile_pixel_width = 256 #print 'coord:', coord #print 'base_zoom:', base_zoom # 256 pixel tile == 2^8 pixel tile, so this is a constant tile_power_of_two = 8 # we want 8x8 fatbits == 2^3 pixel fatbits #TODO: use self.cell_size to find log of 2 to x? pixel_power_of_two = int(log( self.cell_size, 2 )) fat_pixel_width = 2**pixel_power_of_two self.fat_pixel_count = 2**(tile_power_of_two - pixel_power_of_two) # adjust the coord to be the pixel zoom coord = coord.zoomBy(tile_power_of_two - pixel_power_of_two) #print "fat_pixel_count: ", fat_pixel_count #print "coord: ", coord #print 'over_sample_zoom_tile_width: ', over_sample_zoom_tile_width #find the fat_pixel with the maximum photo count max_count = 0 top_count = 0 top_margin = 0 #We should be seeing 64 cells (8x8) output image for row in range( self.fat_pixel_count ): for col in range( self.fat_pixel_count ): ul = coord.right(col).down(row) lr = ul.right().down() #Calculate key for the size dict subquad = Coordinate(ul.row, ul.column, ul.zoom) #print 'subquad:', subquad # these values should always be within (0, 256) x1 = col * fat_pixel_width x2 = (col + 1) * fat_pixel_width y1 = row * fat_pixel_width y2 = (row + 1) * fat_pixel_width #Draw fat pixel based on the returned color based on count (size) in that subquad in the dictionary #Implied that no-data is color[0], above where the img is instantiated enumeration = count_votes( self, subquad ) if max_count < enumeration["photo_count_total"]: max_count = enumeration["photo_count_total"] if top_count < enumeration["photo_count0"]: top_count = enumeration["photo_count0"] if self.output_format == "utf_grid": nw = osm.coordinateLocation(subquad) se = osm.coordinateLocation(subquad.right().down()) lat = (nw.lat - se.lat) / 2 + se.lat lon = (se.lon - nw.lon) / 2 + nw.lon interactivity_array.append( { "photo_count_total":enumeration["photo_count_total"], "woe_id":enumeration["woe_id0"], #"woe_id_lau":enumeration["woe_id0_lau"], #"woe_id_adm2":enumeration["woe_id0_adm2"], #"woe_id_adm1":enumeration["woe_id0_adm1"], "woe_id_adm0":enumeration["woe_id0_adm0"], "name":enumeration["name0"], "photo_count":enumeration["photo_count0"], "margin":enumeration["margin0"], "latitude":lat, "longitude":lon, "x1": str(nw.lon), "y1": str(se.lat), "x2": str(se.lon), "y2": str(nw.lat), "row":str(base_row + row), "col":str(base_column + col), "zoom": coord.zoom } ) elif self.method == "size_log": draw.rectangle((x1, y1, x2, y2), size_color_log(int( enumeration[self.input_field]) )) elif self.method == "size": draw.rectangle((x1, y1, x2, y2), size_color(int( enumeration[self.input_field]) )) elif self.method == "unique_id": draw.rectangle((x1, y1, x2, y2), size_color_unique_id(int( enumeration[self.input_field]) )) if self.output_format == "utf_grid": #print "interactivity_array: ", interactivity_array #grid_utf = create_utf_grid( self, interactivity_array ) grid_utf = { 'grid':['','.'] } if max_count == 0: raise NothingToSeeHere() is_saveable = False # Are we at the last requested zoom? if coord.zoom == self.max_zoom: is_saveable = True # Are we at the minimum viable zoom but with little to no data? if (coord.zoom >= self.min_zoom) and (max_count <= self.min_size): is_saveable = True # Are we viable zoom, viable count, and no ambiguity as to the 100% within margin the winner? if (coord.zoom >= (self.min_zoom + 2)) and (max_count > self.max_size) and ((top_count >= (max_count * self.margin_percent)) or ((max_count - top_count) < self.min_size)): is_saveable = True # Don't want to dig for needles #if coord.zoom == 17 and base_row == 50816 and base_column == 21045: # print '(coord.zoom >= (self.min_zoom + 1)) and ((max_count - top_count) < self.min_size):' # print coord.zoom,(self.min_zoom + 1),max_count, top_count, self.min_size if (coord.zoom >= (self.min_zoom + 1)) and ((max_count - top_count) < self.min_size): #(max_count > self.min_size) and is_saveable = True # and (interactivity_array["margin"] >= self.margin_percent) if is_saveable: #print "should save to DB" #print "interactivity_array: ", interactivity_array saveTileToDatabase( self, interactivity_array ) raise NothingMoreToSeeHere( SaveableResponse(json.dumps(grid_utf)) ) else: return SaveableResponse(json.dumps(grid_utf)) elif self.output_format == "geojson": grid_utf = create_utf_grid( self, interactivity_array ) return SaveableResponse(json.dumps(grid_utf)) else: return img
def renderTile(self, width, height, srs, coord): # return an object with a PIL-like save() method for a tile _width, _height = width / self.scale, height / self.scale img = Image.new("RGB", (_width, _height), (0, 0, 0)) draw = ImageDraw(img) # # Prepare query geometry. # ul = self.layer.projection.coordinateProj(coord) lr = self.layer.projection.coordinateProj(coord.down().right()) x_offset, y_offset = -ul.x, -ul.y x_scale, y_scale = _width / (lr.x - ul.x), _height / (lr.y - ul.y) transform = x_offset, y_offset, x_scale, y_scale buf = (lr.x - ul.x) / 2 bbox = ( "ST_SetSRID(ST_Buffer(ST_MakeBox2D(ST_MakePoint(%.3f, %.3f), ST_MakePoint(%.3f, %.3f)), %.3f, 2), 900913)" % (ul.x, ul.y, lr.x, lr.y, buf) ) colors = product(range(0, 0xFF, 4), range(0, 0xFF, 4), range(0x66, 0xFF, 4)) # # Draw the grid itself and note object color keys as we go. # objects = {} db = connect(database="geodata", user="******").cursor() for (id, type, name, shape) in get_landusages_imposm(db, bbox, *transform): rgb = colors.next() objects[rgb] = "land", type, name, id for geom in getattr(shape, "geoms", [shape]): for ring in [geom.exterior] + list(geom.interiors): draw.polygon(list(ring.coords), fill=rgb) if coord.zoom >= 17: for (id, type, shape) in get_buildings_imposm(db, bbox, *transform): rgb = colors.next() objects[rgb] = "building", name, id for geom in getattr(shape, "geoms", [shape]): for ring in [geom.exterior] + list(geom.interiors): draw.polygon(list(ring.coords), fill=rgb) if coord.zoom >= 15: road_lines = get_roads_imposm(db, bbox, *transform) else: road_lines = get_mainroads_imposm(db, bbox, *transform) + get_motorways_imposm(db, bbox, *transform) for (id, type, name, way) in road_lines: rgb = colors.next() objects[rgb] = "road", type, name, id for geom in getattr(way, "geoms", [way]): stroke = {18: 4, 17: 3}.get(coord.zoom, 2) draw.line(list(geom.coords), fill=rgb, width=stroke) db.close() # # Collect actual rgb values from image and sort them by frequency # so we can build up a grid with the most number of one-and-two-digit # numbers that are also keys into the details array. # data = [(r, g, b) for (r, g, b) in img.getdata()] rgb_counts = {} for rgb in data: rgb_counts[rgb] = rgb_counts.get(rgb, 0) + 1 rgb_counts = sorted(rgb_counts.items(), key=itemgetter(1), reverse=True) rgb_indexes = [key for (key, count) in rgb_counts] # # Build a details array and a two-dimensional column-major grid. # details = [objects.get(rgb, None) for rgb in rgb_indexes] grid = [] for row in range(_height): row, data = data[:_width], data[_width:] row = [rgb_indexes.index(rgb) for rgb in row] grid.append(row) return GridResponse(img.resize((width, height), Image.NEAREST), [details, grid])