def mapdraw(args,colorbar): img = Image.new('RGB',(args['xlen'],args['ylen']),'white') draw = Draw(img) for key,value in args['datamap'].iteritems(): draw.point(value,getrgb(str(key))) img2 = img.resize((args['y'],args['y']), Image.BILINEAR) imgclr = colorbar.resize((args['colorbar'],img2.size[1]), Image.BILINEAR) # ===== ENTIRE IMAGE CREATION W/ TEXT===== imgbox = Image.new('RGB',((300+args['y']+args['colorbar']),(img2.size[1]+200)),args['background']) imgbox.paste(img2,(100,100)) imgbox.paste(imgclr,((200+img2.size[0]),100)) drawbox = Draw(imgbox) title = args['title'] titlesize = 50 # future user input font = truetype("/library/fonts/Arial.ttf",titlesize) smfontsize = 30 # future user input smfont = truetype("/library/fonts/Arial.ttf",smfontsize) titlewidth = font.getsize(title)[0] drawbox.text(((imgbox.size[0]/2 - titlewidth/2), titlesize/2),title,(0,0,0),font=font) drawbox.text(((imgbox.size[0] - 95),100),str(args['max']),(0,0,0),font=smfont) drawbox.text(((imgbox.size[0] - 95),(100 + img2.size[1] - smfontsize)),str(args['min']),(0,0,0),font=smfont) imgbox.show() if 'title' in args: title = args['title']+'_'+str(args['min'])+'_'+str(args['max'])+'.png' else: title = 'output_'+str(args['min'])+'_'+str(args['max'])+'.png' imgbox.save(args['save']+'/'+title)
def draw_text( data, text, color = 255, pos = 'lr' ): from PIL.Image import fromarray from PIL.ImageDraw import Draw from PIL import ImageFont from numpy import asarray font = ImageFont.load_default() image = fromarray( data ) draw = Draw( image ) w, h = draw.textsize( text, font = font ) position = { 'ul': lambda iw, ih, tw, th: ( 2, 0 ), 'ur': lambda iw, ih, tw, th: ( iw - tw - 2, 0 ), 'll': lambda iw, ih, tw, th: ( 2, ih - th ), 'lr': lambda iw, ih, tw, th: ( iw - tw - 2, ih - th ), } pos = position[ pos ]( data.shape[ 1 ], data.shape[ 0 ], w, h ) draw.text( pos, text, fill = color, font = font ) del draw return asarray( image )
def text(self, image, fonts, font_sizes=None, drawings=None, squeeze_factor=0.75, color=None): color = color if color else self._color fonts = tuple([truetype(name, size) for name in fonts for size in font_sizes or (65, 70, 75)]) draw = Draw(image) char_images = [] for c in self._text: font = random.choice(fonts) c_width, c_height = draw.textsize(c, font=font) char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0)) char_draw = Draw(char_image) char_draw.text((0, 0), c, font=font, fill=color) char_image = char_image.crop(char_image.getbbox()) for drawing in drawings: d = getattr(self, drawing) char_image = d(char_image) char_images.append(char_image) width, height = image.size offset = int((width - sum(int(i.size[0] * squeeze_factor) for i in char_images[:-1]) - char_images[-1].size[0]) / 2) for char_image in char_images: c_width, c_height = char_image.size mask = char_image.convert('L').point(lambda i: i * 1.97) image.paste(char_image, (offset, int((height - c_height) / 2)), mask) offset += int(c_width * squeeze_factor) return image
def drawer(image, text): draw = Draw(image) char_images = [] for c in text: font = random.choice(fonts) c_width, c_height = draw.textsize(c, font=font) c_height *= 2 char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0)) char_draw = Draw(char_image) char_draw.text((0, 0), c, font=font, fill=color()) char_image = char_image.crop(char_image.getbbox()) for drawing in drawings: char_image = drawing(char_image) char_images.append(char_image) width, height = image.size offset = int((width - sum(int(i.size[0] * squeeze_factor) for i in char_images[:-1]) - char_images[-1].size[0]) / 2) for char_image in char_images: c_width, c_height = char_image.size mask = char_image.convert('L').point(lambda i: i * 1.97) image.paste(char_image, (offset, int((height - c_height) / 2)), mask) offset += int(c_width * squeeze_factor) return image
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
def inimagehandler(self, code, message, params): im = new('RGBA', (int(params['width']), int(params['height']))) im.putalpha(new('1', (int(params['width']), int(params['height'])))) draw = Draw(im) for count, line in enumerate(message.strip().split('\n')): draw.text((12,15*(count+1)), line, fill='#000000') fh = StringIO() im.save(fh, PIL_TYPE_MAPPING[params['format']]) fh.seek(0) return Response(params['format'], fh.read())
def inimagehandler(self, code, message, params): im = new("RGBA", (int(params["width"]), int(params["height"]))) im.putalpha(new("1", (int(params["width"]), int(params["height"])))) draw = Draw(im) for count, line in enumerate(message.strip().split("\n")): draw.text((12, 15 * (count + 1)), line, fill="#000000") fh = StringIO() im.save(fh, PIL_TYPE_MAPPING[params["format"]]) fh.seek(0) return Response(params["format"], fh.read())
def point(self, patterns, color='black'): hasher = md5() draw = Draw(self.image) for y, pattern in enumerate(patterns): pattern_data = pattern.pattern_data hasher.update(pattern_data) points = [ (x, y) for x, dot in enumerate(_to_bit(pattern_data)) if dot == '1' ] draw.point(points, color) self.hash = hasher.hexdigest()
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
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
def colormap(args): rangelen = args['max'] - args['min'] rangemid = args['min'] + (rangelen / 2) rangemax = args['max'] rangemin = args['min'] cr2 = rgb2hex.linear_gradient(args['colors'][1],args['colors'][2],(int(rangelen/2*1000))+1)['hex'] cr1 = rgb2hex.linear_gradient(args['colors'][0],args['colors'][1],(int(rangelen/2*1000))+1)['hex'] dictlist = {} # === PAIR DATA WITH COLOR MAP === for y,sl in enumerate(args['data']): # for each sublist within dataset (row) for x,i in enumerate(sl): # for each point in sublist (column) val = args['colors'][1] #top half of data range if i > rangemid: if i <= rangemax: val = cr2[int((i - (rangemin + rangelen/2)) * 1000)] else: val = args['colors'][2] #bottom half of data range elif i < rangemid: if i >= rangemin: val = cr1[int((i - rangemin) * 1000)] else: val = args['colors'][0] # mask if 'mask' in args: if i <= args['mask'][0]: val = args['mask'][1] # add to dict if val in dictlist: dictlist[val].append((x,y)) else: dictlist[val] = [(x,y)] args['datamap'] = dictlist # ===== COLORBAR CREATION ===== clr = (cr1 + cr2) clr = clr[::-1000] widthclr = args['colorbar'] heightclr = len(clr) imgclr = Image.new("RGB",(widthclr,heightclr),"white") drawclr = Draw(imgclr) for y,val in enumerate(clr): for x in range(widthclr): drawclr.point((x,y),getrgb(str(val))) return args, imgclr
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
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
def generate_letter(char, font_size, font_name): img_dim = (font_size + font_size / 2,) * 2 img = new_image("RGB", img_dim, (0, 0, 0)) img_draw = Draw(img) #font = PIL.ImageFont.ImageFont() #font.font = PIL.ImageFont.truetype(font_name, font_size) #font.color = tuple( [randrange(126, 256) for i in range(3)] ) font = PIL.ImageFont.truetype(font_name, font_size) color = tuple( [randrange(126, 256) for i in range(3)] ) img_draw.text((0, 0), char, color, font) #img = img_draw.flush() img = img.rotate(randrange(-30, 30), BICUBIC) mask = new_image("L", img.size, 0) mask.paste(img, (0, 0)) return img, mask
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
def drawclock(fontpath,fontsize,fgcolor,bgcolor,style,case,drawLEDs=False): # init font scaledfontsize = pt2pxy(fontsize) font = ImageFont.truetype(size=scaledfontsize,filename=fontpath) lines = decodeLetters(style,case) img = Image.new("RGBA", (pt2pxx(WIDTH), pt2pxy(HEIGHT))) draw = Draw(img) draw.rectangle(((0,0), (pt2pxx(WIDTH),pt2pxy(HEIGHT))), fill=bgcolor) for h in corner_holes: drawhole(draw,h,fgcolor) if drawLEDs: drawleds(draw,led_xs,led_ys,fgcolor) drawletters(draw,lines,font,case,led_xs,led_ys,fgcolor) del draw return img
def decompose_word(img, word, font): x_size = img.size[0] y_size = img.size[1] letters = len(word) array = img_to_array(img) array.shape = (array.shape[1], array.shape[2]) #print word, img.size draw = Draw(Image.new("L",(100,100))) total_font_size = float(draw.textsize(word, font)[0]) data = [] start = 0 for letter in word: # range(0,x_size, x_size / len(word)): #print i*word_size,(i+1)*word_size, array.shape letter_size = draw.textsize(letter, font)[0] size = int(x_size*letter_size/total_font_size) middle = int((start + size) / 2) a = max(0,middle - 64) b = min(x_size, middle + 64) #print acc_size, acc_size+x img = array[:,a:b] if middle - 64 < 0: padding = 255*np.ones((y_size, 64 - middle)) print padding.shape, img.shape img = np.hstack([padding,img]) if middle + 64 > x_size: padding = 255*np.ones((y_size, (middle + 64) - x_size)) print padding.shape, img.shape img = np.hstack([img,padding]) data.append((img,letter)) start = start + size #acc_size = acc_size + x return data
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)
def get_frame(self, n, im_width, im_height): """Return a single frame as a PIL Image. Arguments: n -- the frame index im_width -- the width of the Image to return im_height -- the height of the Image to return """ offset, length, duration = self.frames[n] tiles = self.tiles[offset:offset + length] # Create new blank image img = PILImage.new('RGBA', (im_width, im_height)) draw = PILDraw(img) draw.rectangle(((0, 0), (im_width, im_height)), fill=self.bg) src = self.get_processed_image() # Blit tiles for tile in tiles: x, y, u, v = tile # Fix edge repeat by overlapping tiles 1px x *= self.tile_w - 1 y *= self.tile_h - 1 if x > 0: x += 1 if y > 0: y += 1 # Crop tile u *= self.tile_w v *= self.tile_h box = (u, v, u + self.tile_w, v + self.tile_h) part = src.crop(box) # Paste onto frame box = (x, y, x + self.tile_w, y + self.tile_h) img.paste(part, box) return img
def draw_text(image, text, font_size): font = truetype(join(current_dir, 'static/font.ttf'), font_size) color = '#5C87B2' draw = Draw(image) char_images = [] for ch in text: c_width, c_height = draw.textsize(ch, font=font) char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0)) char_draw = Draw(char_image) char_draw.text((0, 0), ch, font=font, fill=color) char_image = char_image.crop(char_image.getbbox()) char_images.append(char_image) width, height = image.size total = len(char_images) for i, char_image in enumerate(char_images): c_width, c_height = char_image.size mask = char_image.convert('L').point(lambda i: i * 1.97) upper = int((height - c_height) / 2) left = int((width * (i + 1) / (total + 1)) - c_width / 2) image.paste(char_image, (left, upper), mask) return image
def text(self, image, fonts, font_sizes=None, drawings=None, squeeze_factor=0.75, color=None): color = color if color else self._color fonts = tuple([ truetype(name, size) for name in fonts for size in font_sizes or (65, 70, 75) ]) draw = Draw(image) char_images = [] for c in self._text: font = random.choice(fonts) c_width, c_height = draw.textsize(c, font=font) char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0)) char_draw = Draw(char_image) char_draw.text((0, 0), c, font=font, fill=color) char_image = char_image.crop(char_image.getbbox()) for drawing in drawings: d = getattr(self, drawing) char_image = d(char_image) char_images.append(char_image) width, height = image.size offset = int( (width - sum(int(i.size[0] * squeeze_factor) for i in char_images[:-1]) - char_images[-1].size[0]) / 2) for char_image in char_images: c_width, c_height = char_image.size mask = char_image.convert('L').point(lambda i: i * 1.97) image.paste(char_image, (offset, int((height - c_height) / 2)), mask) offset += int(c_width * squeeze_factor) return image
def plot_current_visuals(self, imgs, detections): detections = non_max_suppression(detections, self.opt.conf_thres, self.opt.nms_thres) toImg = transforms.ToPILImage() # we only show the image_batch[0] idx = [] i = 0 for detection in detections: if detection is not None: idx.append(i) i += 1 if len(idx) == 0: self.viz.text('no bbox found with the conf_thres in %.2f' % (self.opt.conf_thres), win=1) return for i in idx: img = toImg(imgs[i, ...]) ori_w, ori_h = img.size img = img.resize((270,270)) detection = detections[i] w,h = img.size draw = Draw(img) if detection is not None: for x1, y1, x2, y2, conf, cls_conf, cls_pred in detection: x1 = float(x1) / ori_w * w y1 = float(y1) / ori_h * h x2 = float(x2) / ori_w * w y2 = float(y2) / ori_h * h x1 = max(0, int(x1)) y1 = max(0, int(y1)) x2 = min(int(x2), w) y2 = min(int(y2), h) draw.rectangle([(x1,y1), (x2,y2)], outline=(255,0,0)) #print(cls_pred) name = self.class_names[int(cls_pred)] name += "=%.4f" % float(cls_conf) f = ImageFont.truetype("fonts-japanese-gothic.ttf", 15) draw.text((x1,y1), name, 'blue', font=f) self.viz.image(np.array(img).transpose((2,0,1)), win=i+2)
def draw_text(image, text, font_size): font = truetype(join(current_dir, 'static/DroidSansFallback.ttf'), font_size) color = '#5C87B2' draw = Draw(image) char_images = [] for ch in text: c_width, c_height = draw.textsize(ch, font=font) char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0)) char_draw = Draw(char_image) char_draw.text((0, 0), ch, font=font, fill=color) char_image = char_image.crop(char_image.getbbox()) char_images.append(char_image) width, height = image.size total = len(char_images) for i, char_image in enumerate(char_images): c_width, c_height = char_image.size mask = char_image.convert('L').point(lambda i: i * 1.97) upper = int((height - c_height) / 2) left = int((width * (i + 1) / (total + 1)) - c_width / 2) image.paste(char_image, (left, upper), mask) return image
def drawPoly(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) drawIm.line([ polyArr[len(polyArr) - 2], polyArr[len(polyArr) - 1], polyArr[0], polyArr[1] ], fill=fillColor, width=5) return im
def rasterize_geometry(geometry: List[Polygon], tile: Tile, source_zoom: int = 18) -> np.ndarray: wm_geometry = [transform(xy, shape) for shape in geometry] res = get_res(tile, source_zoom=source_zoom) wm_bounds = xy_bounds(tile) def imgspace_transform(xs, ys): xs = np.array(xs) ys = np.array(ys) xs -= wm_bounds.left ys -= wm_bounds.bottom xs /= (wm_bounds.right - wm_bounds.left) ys /= (wm_bounds.top - wm_bounds.bottom) xs *= res ys *= res ys = res - ys return xs, ys img_geometry = [ transform(imgspace_transform, shape) for shape in wm_geometry ] img_geometry = [ list(poly) if type(poly) == MultiPolygon else poly for poly in img_geometry ] img = Image.new('L', (res, res)) draw = Draw(img) for polygon in img_geometry: if type(polygon) != Polygon: print(f"Skipping non-polygon {type(polygon)}!") continue draw.polygon(list(polygon.exterior.coords), fill=1) for interior_hole in polygon.interiors: draw.polygon(list(interior_hole.coords), fill=0) ar = np.array(img, dtype=np.float32) return ar
def rectangle_to_vinyle(np_img): """Convert lines into circles, from left=in to right=out (7min/img)""" min_radius = np_img.shape[1] // 2 max_radius = np_img.shape[1] + min_radius side_length = max_radius * 2 pil_circle = Image.new('RGB', (side_length, side_length), color='white') drawer = Draw(pil_circle, mode='RGB') degree_step = 180.0 / np_img.shape[0] #angle is 0 at 3 o'clock, increasing clockwise get_angle = lambda x: 270 - x * degree_step for i, col in tqdm(enumerate(np.transpose(np_img, axes=[1,0,2])), total=np_img.shape[1]): x0 = side_length // 2 - min_radius - i x1 = side_length // 2 + min_radius + i for j, pixel in enumerate(col): drawer.arc([x0, x0, x1, x1], get_angle(j+1), get_angle(j), tuple(pixel), 2) drawer.arc([x0, x0, x1, x1], get_angle(-j), get_angle(-j-1), tuple(pixel), 2) return pil_circle
def test_img(): import random s_width, s_height = 120, 4 image = Image.new("RGB", (120, 40), (255, 255, 255)) draw = Draw(image) # image.show() # im = Image.new("RGB", ) fontpath = "./fonts/Arial.ttf" font = ImageFont.truetype(fontpath, 35) draw.text((0, 0), "1", font=font, fill=(0, 0, 0)) w, h = draw.textsize("2", font=font) dx = random.randint(0, 4) dy = random.randint(0, 6) im = Image.new('RGBA', (w + dx, h + dy)) Draw(im).text((dx, dy), "2", font=font, fill=(56, 90, 0)) im = im.rotate(random.uniform(-90, 90), Image.BILINEAR, expand=1) r, g, b, a = im.split() image.paste(im, (10, int((s_height - h) / 2)), mask=a) # im.show() image.show()
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
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
def create_captcha_image(self, chars, color, background): """Create the CAPTCHA image itself. :param chars: text to be generated. :param color: color of the text. :param background: color of the background. The color should be a tuple of 3 numbers, such as (0, 255, 255). """ image = Image.new('RGB', (self._width, self._height), background) draw = Draw(image) def is_chinese(uchar): if uchar >= u'\u4e00' and uchar<=u'\u9fa5': return True else: return False def _draw_character(c,font): #if is_chinese(c): #font = random.choice(self.truefonts(index=1)) #else: #font = random.choice(self.truefonts(index=0)) #font = random.choice(self.truefonts) w, h = draw.textsize(c, font=font) #dx = random.randint(0, 4) #dy = random.randint(0, 6) #im = Image.new('RGBA', (w + dx, h + dy)) im = Image.new('RGBA', (w, h)) #Draw(im).text((dx, dy), c, font=font, fill=color) Draw(im).text((0, 0), c, font=font, fill=color) # rotate im = im.crop(im.getbbox()) im = im.rotate(random.uniform(-50, 50), Image.BILINEAR,expand=1) #return im # warp dx = w * random.uniform(0.1, 0.3) dy = h * random.uniform(0.2, 0.3) x1 = int(random.uniform(-dx, dx)) y1 = int(random.uniform(-dy, dy)) x2 = int(random.uniform(-dx, dx)) y2 = int(random.uniform(-dy, dy)) w2 = w + abs(x1) + abs(x2) h2 = h + abs(y1) + abs(y2) data = ( x1, y1, -x1, h2 - y2, w2 + x2, h2 + y2, w2 - x2, -y1, ) im = im.resize((w2, h2)) im = im.transform((w, h), Image.QUAD, data) return im images = [] for c in chars: if not c.encode('utf-8').isalnum():#中文 font = random.choice(self.truefonts2) else: font = random.choice(self.truefonts) images.append(_draw_character(c,font)) text_width = sum([im.size[0] for im in images]) width = max(text_width, self._width) #image = image.resize((width, self._height)) average = int(text_width / len(chars)) rand = int(0.1 * average) #offset = int(average * 0.1) def left_w(last_index): _left_w=0 index_=0 if last_index==-1: return text_width for im in images: if index_<=last_index: index_+=1 continue _left_w+=im.size[0] index_+=1 return _left_w offset=0 offset=random.randint(offset,width-text_width) #print('chars',chars) index_=0 for im in images: w, h = im.size rand_y_off=0 if self._height>h: rand_y_off=random.randint(-7,self._height-h) image.paste(im, (offset,rand_y_off ),mask=Image.merge("L", (im.split()[3],))) off=self._width-(offset+w)-left_w(index_) if off<0: off=0 offset = offset+w+random.randint(-int(w/2),off) index_+=1 #if image.size[0] > self._width : #image = image.resize((self._width, self._height)) return image
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
c = 0 lines = str(len(system)) for s in system: print(str(c) + '/' + lines, end='\r') if s == '-': d -= 60 elif s == '+': d += 60 elif s == 'h': currentPos = line(currentPos, dist, d, (255, 228, 122)) c += 1 kochSystem = 'h' for i in range(7): kochSystem = update(kochSystem) w = len(kochSystem) // 1893 * 739 h = len(kochSystem) // 7 distance = (len(kochSystem) / w)**2 currentPos = (0, 1) print(w, h) im = Image.new('RGB', (w, h)) draw = Draw(im) drawKoch(kochSystem, distance) im = im.transpose(Image.FLIP_TOP_BOTTOM) print('ready') im.save('kochCurve.jpeg')
def background(self, image): Draw(image).rectangle([(0, 0), image.size], fill=self.random_color(238, 255)) return image
plt.xlim(0,1000) plt.ylim(1500,0) plt.savefig(output_directory + 'compare_frame_{}.png'.format(i)) 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
def display_pil_image(im): """Displayhook function for PIL Images, rendered as PNG.""" b = BytesIO() im.save(b, format='png') data = b.getvalue() ip_img = display.Image(data=data, format='png', embed=True) return ip_img._repr_png_() # register display func with PNG formatter: png_formatter = get_ipython().display_formatter.formatters['image/png'] dpi = png_formatter.for_type(Image.Image, display_pil_image) # <codecell> 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)) # img.save("foo.png") imshow(img) # <codecell>
def create_captcha_image(self, chars, color, background, for_training=False): """Create the CAPTCHA image itself. :param chars: text to be generated. :param color: color of the text. :param background: color of the background. The color should be a tuple of 3 numbers, such as (0, 255, 255). """ image = Image.new('RGB', (self._width, self._height), background) draw = Draw(image) def _draw_character(c): font = random.choice(self.truefonts) w, h = draw.textsize(c, font=font) dx = random.randint(0, 4) dy = random.randint(0, 6) im = Image.new('RGBA', (w + dx, h + dy)) Draw(im).text((dx, dy), c, font=font, fill=color) # rotate im = im.crop(im.getbbox()) im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1) # warp dx = w * random.uniform(0.1, 0.3) dy = h * random.uniform(0.2, 0.3) x1 = int(random.uniform(-dx, dx)) y1 = int(random.uniform(-dy, dy)) x2 = int(random.uniform(-dx, dx)) y2 = int(random.uniform(-dy, dy)) w2 = w + abs(x1) + abs(x2) h2 = h + abs(y1) + abs(y2) data = ( x1, y1, -x1, h2 - y2, w2 + x2, h2 + y2, w2 - x2, -y1, ) im = im.resize((w2, h2)) im = im.transform((w, h), Image.QUAD, data) return im images = [] actual_char_inds = [] ind = 0 for c in chars: if random.random() > 0.5: images.append(_draw_character(" ")) ind += 1 actual_char_inds.append(ind) ind += 1 images.append(_draw_character(c)) text_width = sum([im.size[0] for im in images]) width = max(text_width, self._width) image = image.resize((width, self._height)) if for_training: return_obj = {"char_onlys": [], "final": None} blank = Image.new('RGB', (width, self._height), (255, 255, 255)) average = int(text_width / len(chars)) rand = int(0.25 * average) offset = int(average * 0.1) for i, im in enumerate(images): w, h = im.size mask = im.convert('L').point(table) upper_left = (offset, int((self._height - h) / 2)) if i in actual_char_inds and for_training: char_only_im = blank.copy() char_only_im.paste(im, upper_left, mask) return_obj["char_onlys"].append(char_only_im) image.paste(im, upper_left, mask) offset = offset + w + random.randint(-rand, 0) if width > self._width: image = image.resize((self._width, self._height)) if for_training: return_obj["final"] = image return return_obj else: return image
def create_captcha_image(self, chars, color, background): """Create the CAPTCHA image itself. :param chars: text to be generated. :param color: color of the text. :param background: color of the background. The color should be a tuple of 3 numbers, such as (0, 255, 255). """ image = Image.new('RGB', (self._width, self._height), background) draw = Draw(image) def _draw_character(c): font = random.choice(self.truefonts) w, h = draw.textsize(c, font=font) dx = random.randint(0, 4) dy = random.randint(0, 6) im = Image.new('RGBA', (w + dx, h + dy)) Draw(im).text((dx, dy), c, font=font, fill=color) # rotate im = im.crop(im.getbbox()) im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1) # warp dx = w * random.uniform(0.1, 0.3) dy = h * random.uniform(0.2, 0.3) x1 = int(random.uniform(-dx, dx)) y1 = int(random.uniform(-dy, dy)) x2 = int(random.uniform(-dx, dx)) y2 = int(random.uniform(-dy, dy)) w2 = w + abs(x1) + abs(x2) h2 = h + abs(y1) + abs(y2) data = ( x1, y1, -x1, h2 - y2, w2 + x2, h2 + y2, w2 - x2, -y1, ) im = im.resize((w2, h2)) im = im.transform((w, h), Image.QUAD, data) return im images = [] for c in chars: images.append(_draw_character(c)) text_width = sum([im.size[0] for im in images]) width = max(text_width, self._width) image = image.resize((width, self._height)) average = int(text_width / len(chars)) rand = int(0.25 * average) offset = int(average * 0.1) for im in images: w, h = im.size mask = im.convert('L').point(table) image.paste(im, (offset, int((self._height - h) / 2)), mask) offset = offset + w + random.randint(-rand, 0) if width > self._width: image = image.resize((self._width, self._height)) return image
def main(argv): count = 32 limit = None seed = None validate = False incremental = None out_filename = None img_size = 256 min_size = 2 max_size = 192 mean = 24 # variance = 2 variance = 2 pack = pack_dense arg_it = iter(argv[1:]) for arg in arg_it: if arg[0] == '-': if arg == '-c': count = int(next(arg_it)) elif arg == '-i': incremental = next(arg_it) elif arg == '-l': limit = int(next(arg_it)) elif arg == '-p': arg = next(arg_it) pack = globals().get('pack_' + arg) if pack is None: print("Unknown pack method '{}'".format(arg), file=stderr) usage(argv) elif arg == '-s': seed = next(arg_it) elif arg == '-v': validate = True else: print("Unknown opiton '{}'.".format(arg), file=stderr) usage(argv) elif out_filename is None: out_filename = arg else: usage(argv) if out_filename is None: usage(argv) rng = Random() rng.seed(seed) boxes = random_boxes(rng, count, min_size, max_size, mean, variance) if limit is not None: boxes = sorted(boxes, key=lambda b: (b.size(1), b.size(0)), reverse=True) boxes = boxes[:limit] packed = pack(boxes, img_size, img_size, incremental=incremental, validate=validate) if validate: assert not have_intersection(packed) page_count = 0 for box in packed: page_count = max(page_count, box.page() + 1) img = Image.new('RGBA', (img_size * page_count, img_size), (0, 0, 0, 255)) d = Draw(img) for i, box in enumerate(packed): color = hsv_to_rgb(halton(i, 2), 1, 1) outline = tuple(map(lambda x: int(x * 255), color)) + (255, ) fill = tuple(map(lambda x: int(x * 63 + 192), color)) + (255, ) offset = Vector(img_size * box.page(), 0) p0 = tuple(box.min() + offset) p1 = tuple(box.max() + offset - Vector(1, 1)) d.rectangle([p0, p1], outline=outline, fill=fill) img.save('{}.png'.format(out_filename)) area = sum(map(Box.area, packed)) max_height = 0 for box in packed: if box.page() == page_count - 1: max_height = max(max_height, box.max(1)) atlas_area = img_size * (img_size * (page_count - 1) + max_height) print("Area: {:7d}px^2".format(area)) print("Atlas area: {:7d}px^2".format(atlas_area)) print("Occupancy: {:4.2f}%".format(area / atlas_area * 100))
def draw_gameover(self, draw: ImageDraw.Draw): text = 'GAME OVER' text_width, text_height = draw.textsize(text) draw.text((Vector(*canvas_size) - (text_width, text_height)) / 2, text, fill=(255, 255, 255, 255))
def create_captcha_image(self, chars, color, background): """Create the CAPTCHA image itself. :param chars: text to be generated. :param color: color of the text. :param background: color of the background. The color should be a tuple of 3 numbers, such as (0, 255, 255). """ image = Image.new('RGB', (self._width, self._height), background) draw = Draw(image) global getposlist poslist = [] flaglist = [] def _draw_character(c): font = random.choice(self.truefonts) w, h = draw.textsize(c, font=font) dx = random.randint(0, 4) dy = random.randint(0, 6) im = Image.new('RGBA', (w + dx, h + dy)) Draw(im).text((dx, dy), c, font=font, fill=color) # rotate im = im.crop(im.getbbox()) im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1) # warp dx = w * random.uniform(0.1, 0.3) dy = h * random.uniform(0.2, 0.3) x1 = int(random.uniform(-dx, dx)) y1 = int(random.uniform(-dy, dy)) x2 = int(random.uniform(-dx, dx)) y2 = int(random.uniform(-dy, dy)) w2 = w + abs(x1) + abs(x2) h2 = h + abs(y1) + abs(y2) data = ( x1, y1, -x1, h2 - y2, w2 + x2, h2 + y2, w2 - x2, -y1, ) im = im.resize((w2, h2)) im = im.transform((w, h), Image.QUAD, data) return im images = [] for c in chars: if random.random() > 0.5: images.append(_draw_character(" ")) flaglist.append(0) images.append(_draw_character(c)) flaglist.append(1) text_width = sum([im.size[0] for im in images]) width = max(text_width, self._width) image = image.resize((width, self._height)) average = int(text_width / len(chars)) rand = int(0.25 * average) offset = int(average * 0.1) str_count = 0 for i, im in enumerate(images): w, h = im.size y = int((self._height - h) / 2) # 只有非空字符串的位置才会添加到poslist(位置列表) if (flaglist[i]): idx = self.dictset.index(chars[str_count]) poslist.append([idx, offset, y, w + offset, h + y]) str_count += 1 mask = im.convert('L').point(table) image.paste(im, (offset, y), mask) offset = offset + w + random.randint(-rand, 0) if width > self._width: image = image.resize((self._width, self._height)) divtemp = width / self._width for l in poslist: l[1] = int(l[1] / divtemp) l[3] = int(l[3] / divtemp) if self.normalized: for l in poslist: l[1], l[3] = l[1] / self._width, l[3] / self._width l[2], l[4] = l[2] / self._height, l[4] / self._height self.poslist.append(poslist) return image
def draw_gamestate(self, draw: ImageDraw.Draw): # food (cross) food_tile_center = to_canvas_coord(self.game.food_position) draw.ink = 4 draw.point(food_tile_center + (-1, 0)) draw.point(food_tile_center + (0, -1)) draw.point(food_tile_center) draw.point(food_tile_center + (1, 0)) draw.point(food_tile_center + (0, 1)) # snake body draw.ink = 3 draw.fill = 3 snake_head_tile_center = to_canvas_coord(self.game.snake.head_position) tile_center = snake_head_tile_center is_first = True labs = partial(looparound_vector, board_size) tile_position = self.game.snake.head_position for move in reversed(self.game.snake.movements): start_offset = NULL_VECTOR end_offset = NULL_VECTOR if move.direction == UP: dir_vector = Vector(0, 1) start_offset = Vector(0, -1) elif move.direction == DOWN: dir_vector = Vector(0, -1) end_offset = Vector(0, 1) elif move.direction == LEFT: dir_vector = Vector(1, 0) start_offset = Vector(-1, 0) elif move.direction == RIGHT: dir_vector = Vector(-1, 0) end_offset = Vector(1, 0) for i in range(move.amount): tile_position = labs(tile_position + dir_vector) tile_center = to_canvas_coord(tile_position) if move.direction == UP and tile_position.y == board_size.h - 1: end_offset += (0, 1) elif move.direction == LEFT and tile_position.x == board_size.w - 1: end_offset += (1, 0) draw.rectangle([ tile_center + (-1, -1) + start_offset, tile_center + (1, 1) + end_offset ]) if is_first: # snake head end_offset = NULL_VECTOR if move.direction == UP and self.game.snake.head_position.y == board_size.h - 1: end_offset += (0, 1) elif move.direction == LEFT and self.game.snake.head_position.x == board_size.w - 1: end_offset += (1, 0) draw.rectangle([ snake_head_tile_center + (-1, -1), snake_head_tile_center + (1, 1) + end_offset ]) is_first = False # snake eyes last_movement_dir = self.game.snake.movements[-1].direction if last_movement_dir == UP or last_movement_dir == DOWN: draw.point(snake_head_tile_center + (-1, 0), 2) draw.point(snake_head_tile_center + (1, 0), 2) else: draw.point(snake_head_tile_center + (0, -1), 2) draw.point(snake_head_tile_center + (0, 1), 2)
def draw_detect_point(img, fp): draw = Draw(img) for xy in chain(zip(*l_indexes), zip(*r_indexes)): draw.point(xy[::-1], 'red') img.save(fp)
def draw_text(text, font_spec, text_color, xy=None, anchor=None, box_color=None, box_padding=0, border_color=None, border_width=0, image=None): """Draws centered text on an image, optionally in a box.""" draw = Draw(image) text_size = font_spec['size'] font = ImageFont.truetype(font_spec['file'], size=text_size) # Measure the width of each character. character_widths = [] for character in text: # Override the measured width, if specified. width_overrides = font_spec['width_overrides'] if character in width_overrides.keys(): character_width = width_overrides[character] else: character_width, _ = draw.textsize(character, font) character_widths.append(character_width) text_width = sum(character_widths) # If any xy is specified, use it. text_height = font_spec['height'] if xy: x = xy[0] - text_width // 2 y = xy[1] - text_height // 2 # If any anchor is specified, adjust the xy. if anchor == 'center': x = image.width // 2 - text_width // 2 y = image.height // 2 - text_height // 2 elif anchor == 'center_x': x = image.width // 2 - text_width // 2 elif anchor == 'center_y': y = image.height // 2 - text_height // 2 elif anchor == 'bottom_right': x = image.width - box_padding - border_width - text_width y = image.height - box_padding - border_width - text_height # Draw the box background and border. box_xy = [ x - box_padding, y - box_padding, x + text_width + box_padding, y + text_height + box_padding ] border_xy = [ box_xy[0] - border_width, box_xy[1] - border_width, box_xy[2] + border_width, box_xy[3] + border_width ] if border_color: draw.rectangle(border_xy, border_color) if box_color: draw.rectangle(box_xy, box_color) # Draw the text character by character. y -= font_spec['y_offset'] for index in range(len(text)): character = text[index] draw.text((x, y), character, text_color, font) x += character_widths[index]
def _background(self): """绘制背景""" Draw(self._image).rectangle([(0, 0), self._image.size], fill=random_color(230, 255))
def add_curve(image, color, bbox, startAg, endAg): Draw(image).arc(bbox, startAg, endAg, fill=color) return image
icon_height = 0 # Font laden und rausbekommen, wie gross der Button werden muss ttf = '/Library/Fonts/Arial Narrow Bold.ttf' font = truetype(ttf, 12, encoding='unic') text_width, _ = font.getsize(label) width = text_width + 2 * args.padding + icon_width # jetzt den Hintergrund in den Button reinkopieren button = Image.new('RGBA', (width, height * 2)) button.paste(background, (0, 0)) button.paste(flip(background), (0, height)) button.paste(right, (width-5, 0)) button.paste(flip(right), (width-5, height)) # das Icon muss auch rein, wenn wir eines haben if icon: alpha_channel = icon.split()[3] mask = Image.eval(alpha_channel, lambda a: 255 if a >=128 else 0) for offs in [0, height]: button.paste(icon, (7, offs + int(height/2.0-icon_height/2.0)), mask) # dann die Beschriftung reinmalen draw = Draw(button) draw.text((icon_width + args.padding, upper_text), label, font=font, fill=args.text_color) draw.text((icon_width + args.padding, lower_text), label, font=font, fill=args.text_color) # und schliesslich nur noch den Button speichern #button.show() button.save(filename, 'PNG')
def _draw_berthed_ship_box( self, draw: ImageDraw.Draw, top_left_corner: Tuple[int, int], width: int, ship: pd.Series ) -> int: """ Draws a berthed ship's information on a box. Args: draw: The ImageDraw instance to draw on the desired canvas. top_left_corner: Where to start the box. width: The fixed horizontal dimension of the box. ship: Source of the information for the ship, obtained from the LogKeeper. Returns: The bottom y coordinate of the box, so that further elements may be drawn after it """ berco = get_ship_berth_number(ship) # Alternate colors for different designated berthing numbers. if berco is None or berco % 2 == 0: background_color = self.colors['berthed_ship_box_background_even'] else: background_color = self.colors['berthed_ship_box_background_odd'] name_str = ship['Navio'] name_font = self.fonts['large'] # Resize the font until the name fits within the specified width. while (name_font.size > 12) and (name_font.getsize(name_str)[0] > (width - 30)): name_font = self._load_font(self.font_path, max(1, name_font.size - 1)) name_font_height = name_font.getsize('X')[1] berco_str = 'Berço ' + str(berco) berco_font = self.fonts['medium'] berco_font_height = berco_font.getsize('X')[1] margin = (20 * self.scaler_value) bottom_y = int(top_left_corner[1] + name_font_height + berco_font_height + margin * 3) draw.rectangle( ( top_left_corner[0], top_left_corner[1], top_left_corner[0] + width, bottom_y ), fill=background_color ) draw.multiline_text( (top_left_corner[0] + margin, top_left_corner[1] + margin), name_str, fill=self.colors['berthed_ship_box_text'], font=name_font ) if berco is not None: draw.multiline_text( (top_left_corner[0] + margin, top_left_corner[1] + name_font_height + margin * 2), berco_str, fill=self.colors['berthed_ship_box_text'], font=berco_font ) return bottom_y
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
def create_captcha_image(self, chars, color, background1, background2): """Create the CAPTCHA image itself. :param chars: text to be generated. :param color: color of the text. :param background: color of the background. The color should be a tuple of 3 numbers, such as (0, 255, 255). """ image1 = Image.new('RGB', (self._width, self._height), background1) image2 = Image.new('RGB', (self._width, self._height), background2) draw1 = Draw(image1) draw1 = Draw(image2) def _draw_character(c, font, dx, dy): # font = random.choice(self.truefonts) # font = load_default().font # print(font) w, h = draw1.textsize(c, font=font) # dx = random.randint(0, 4) # dy = random.randint(0, 6) im = Image.new('RGBA', (w + dx, h + dy)) Draw(im).text((dx, dy), c, font=font, fill=color) # im.show() # rotate # im = im.crop(im.getbbox()) # im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1) # # # warp # dx = w * random.uniform(0.1, 0.3) # dy = h * random.uniform(0.2, 0.3) # x1 = int(random.uniform(-dx, dx)) # y1 = int(random.uniform(-dy, dy)) # x2 = int(random.uniform(-dx, dx)) # y2 = int(random.uniform(-dy, dy)) # w2 = w + abs(x1) + abs(x2) # h2 = h + abs(y1) + abs(y2) # data = ( # x1, y1, # -x1, h2 - y2, # w2 + x2, h2 + y2, # w2 - x2, -y1, # ) # im = im.resize((w2, h2)) # im = im.transform((w, h), Image.QUAD, data) return im images = [] font = random.choice(self.truefonts) dx = random.randint(0, 4) dy = random.randint(0, 6) # chars = "2256" for c in chars: # if random.random() > 0.5: # images.append(_draw_character(" ")) images.append(_draw_character(c, font, dx, dy)) text_width = sum([im.size[0] for im in images]) width = max(text_width, self._width) image1 = image1.resize((width, self._height)) image2 = image2.resize((width, self._height)) average = int(text_width / len(chars)) rand = int(0.25 * average) offset = int(average * 0.1) for im in images: w, h = im.size # im.show() r, g, b, a = im.split() print(r, g, b, a) # mask = trans(im) mask = im.convert('L').point(table) image1.paste(im, (offset, int((self._height - h) / 2)), mask=a) image2.paste(im, (offset, int((self._height - h) / 2)), mask=a) offset = offset + w + random.randint(-rand, 0) if width > self._width: image1 = image1.resize((self._width, self._height)) image2 = image2.resize((self._width, self._height)) return image1, image2
def draw_glyph(self, img, codepoint): draw = Draw(img) draw.text((0, 0), unichr(codepoint), font=self.tt, fill='#000000') return img
def make_text(text: str, box=(0, 0), init_font_size=76, align='left', font_path='', color=(0, 0, 0, 255), stroke=None): # split text into individual words, then draw them sequentially. # in fact more efficient than previously thought. # NOTE: arg `align` is NYI, probably impossible words = text.split() canvas = Image.new('RGBA', box, color=(255, 255, 255, 0)) # method scope x, y = 0, 0 font_size = init_font_size while True: # (re-)initiate canvas canvas = Image.new('RGBA', box, color=(255, 255, 255, 0)) draw = Draw(canvas) # for each font size, first fill the width. # if the height exceeds the size of the box, reduce font size. # repeat font size reduction until fits. if 0 < font_size <= 16: font_size -= 1 elif 16 < font_size < 32: font_size -= 2 elif font_size >= 32: font_size -= 4 else: break font = truetype(font_path, size=font_size) space_width = draw.textsize(' ', font=font)[0] line_height = int(font_size * 1.2) # start filling words idx = 0 # position in list `words` y = 0 while idx < len(words): # words not depleted # new line x = 0 word = words[idx] word_width = draw.textsize(word, font=font)[0] # skip this size if even a single word won't fit if word_width > box[0]: break # fill line until it would overflow while x + word_width <= box[0]: draw.text( (x, y - font_size // 10), word, fill=color if stroke is None else WHITE, font=font, stroke_fill=stroke, # stroke width: 2 is the bare minimum stroke_width=(max(font_size // 20, 2) if stroke is not None else 0)) x += word_width + space_width idx += 1 if idx >= len(words): break word = words[idx] word_width = draw.textsize(words[idx], font=font)[0] y += line_height if y <= box[1] and idx == len(words): return canvas
def draw_game_number(draw: ImageDraw.Draw, shuffle_num: int) -> None: text = f"Match {shuffle_num + 1}" draw.text((10, 10), text, font=shuffle_font, fill=(81, 81, 81, 255))
((3, 8), (9, 8)), ((16, 8), (18, 8)), ((8, 9), (18, 9)), ((11, 12), (18, 12)), ((11, 13), (18, 13)), ((8, 16), (18, 16)), ((3, 19), (8, 19)), ((3, 23), (8, 22)), ] # <codecell> 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
def image(self, user, width, height): """Generates an image with a calendar view.""" # Show a calendar relative to the current date. try: time = self._local_time.now(user) except DataError as e: raise ContentError(e) # Get the number of events per day from the API. event_counts = self._event_counts(time, user) # Create a blank image. image = Image.new(mode='RGB', size=(width, height), color=BACKGROUND_COLOR) draw = Draw(image) # Get this month's calendar. try: firstweekday = WEEK_DAYS[user.get('first_week_day')] except KeyError: firstweekday = SUNDAY calendar = Calendar(firstweekday=firstweekday) weeks = calendar.monthdayscalendar(time.year, time.month) # Determine the spacing of the days in the image. x_stride = width // (DAYS_IN_WEEK + 1) y_stride = height // (len(weeks) + 1) # Draw each week in a row. for week_index in range(len(weeks)): week = weeks[week_index] # Draw each day in a column. for day_index in range(len(week)): day = week[day_index] # Ignore days from other months. if day == 0: continue # Determine the position of this day in the image. x = (day_index + 1) * x_stride y = (week_index + 1) * y_stride # Mark the current day with a squircle. if day == time.day: squircle = Image.open(SQUIRCLE_FILE).convert(mode='RGBA') squircle_xy = (x - squircle.width // 2, y - squircle.height // 2) draw.bitmap(squircle_xy, squircle, HIGHLIGHT_COLOR) number_color = TODAY_COLOR event_color = TODAY_COLOR else: number_color = NUMBER_COLOR event_color = HIGHLIGHT_COLOR # Draw the day of the month number. number = str(day) draw_text(number, SUBVARIO_CONDENSED_MEDIUM, number_color, xy=(x, y - NUMBER_Y_OFFSET), image=image) # Draw a dot for each event. num_events = min(MAX_EVENTS, event_counts[day]) dot = Image.open(DOT_FILE).convert(mode='RGBA') if num_events > 0: events_width = (num_events * dot.width + (num_events - 1) * DOT_MARGIN) for event_index in range(num_events): event_offset = (event_index * (dot.width + DOT_MARGIN) - events_width // 2) dot_xy = [ x + event_offset, y + DOT_OFFSET - dot.width // 2 ] draw.bitmap(dot_xy, dot, event_color) return image
filename = 'button-small-%s.png' % label.lower().replace(' ', '-') # Hintergrund zusammenbauen gradients = Image.open('generate-button-small.png') y = 0 height = 23 background = gradients.crop((0, y, 200, height)) right = gradients.crop((203, 0, 208, height)) # Font laden und rausbekommen, wie gross der Button werden muss ttf = '/Library/Fonts/Arial Narrow Bold.ttf' font = truetype(ttf, 12, encoding='unic') text_width, _ = font.getsize(label) width = text_width + 2 * args.padding # jetzt den Hintergrund in den Button reinkopieren button = Image.new('RGBA', (width, height * 2)) button.paste(background, (0, 0)) button.paste(flip(background), (0, height)) button.paste(right, (width-5, 0)) button.paste(flip(right), (width-5, height)) # dann die Beschriftung reinmalen draw = Draw(button) draw.text((args.padding, 0+3), label, font=font, fill=args.text_color) draw.text((args.padding, 23+4), label, font=font, fill=args.text_color) # und schliesslich nur noch den Button speichern #button.show() button.save(filename, 'PNG')