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 getcode(request): # 自己画图片。初始化画笔和画布 mode = 'RGB' size = (180, 60) # 调取颜色 red = get_color() green = get_color() blue = get_color() bg_color = (red, green, blue) # 准备画布 image = Image.new(mode, size, color=bg_color) # 准备画布 draw = ImageDraw(image, mode=mode) # 画笔 # 字体 font = ImageFont.truetype(font=settings.FONT_PATH, size=50) code = generate_code() # 产生验证码 request.session['code'] = code # 往画布画验证码 # 取一个,画一个fill填充颜色 for a in range(4): fill_color = (get_color(), get_color(), get_color()) draw.text(xy=(47 * a, 0), text=code[a], font=font, fill=fill_color) for a in range(500): fill_color = (get_color(), get_color(), get_color()) import random #位置 position = (random.randrange(201), random.randrange(81)) # 画点 draw.point(xy=position, fill=fill_color) # 字节IO by = BytesIO() image.save(by, 'png') return HttpResponse(by.getvalue(), content_type='image/png')
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 get_verify_code(request): mode = "RGB" size = (100, 40) red = get_color() green = get_color() blue = get_color() color_bg = (red, green, blue) image = Image.new(mode=mode, size=size, color=color_bg) imagedraw = ImageDraw(image, mode=mode) imagefont = ImageFont.truetype(settings.FONT_PATH, 40) verify_code = generate_code() request.session['verify_code'] = verify_code # 存到session中用于用户登录 for i in range(4): fill = (get_color(), get_color(), get_color()) imagedraw.text(xy=(25 * i, 0), text=verify_code[i], font=imagefont, fill=fill) for i in range(700): fill = (get_color(), get_color(), get_color()) xy = (random.randrange(100), random.randrange(40)) imagedraw.point(xy=xy, fill=fill) fp = BytesIO() image.save(fp, "png") return HttpResponse(fp.getvalue(), content_type="image/png")
def render(days): units = { class_.name.split(' - ')[0] for class_ in chain.from_iterable(days.values()) } colours = build_colours(units) img = Image.new( 'RGBA', ( (NUM_DAYS * DAY_WIDTH), (HOURS * HOUR_HEIGHT) ), color='white' ) draw = ImageDraw(img) draw_weekday_names(draw) score_hour_lines(draw) draw_class_boxes(draw, days, colours) # trim to hours where classes actually occur return img.crop(( 0, int(7.5 * HOUR_HEIGHT), # classes start at 8am NUM_DAYS * DAY_WIDTH, ((18 + 1) * HOUR_HEIGHT) # classes finish at 6pm (1800 hours in 24 hour time) # but we add to include that last hour (5-6pm) ))
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 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 draw_boxes(image_path, measures): image = Image.open(image_path).convert('RGBA') overlay = Image.new('RGBA', image.size) image_draw = ImageDraw(overlay) for measure in measures: image_draw.rectangle([ int(measure['left']), int(measure['top']), int(measure['right']), int(measure['bottom']) ], fill='#00FFFF1B') for m, measure in enumerate(measures): image_draw.rectangle([ int(measure['left']), int(measure['top']), int(measure['right']), int(measure['bottom']) ], outline='#008888', width=2) result_image = Image.alpha_composite(image, overlay).convert('RGB') target_dir = os.path.join(os.path.dirname(image_path), 'bboxes') os.makedirs(target_dir, exist_ok=True) basename = os.path.basename(image_path) result_path = os.path.join(target_dir, basename) result_image.save(result_path)
def get(self, request): color_bg = (get_color(), get_color(), get_color()) image = Image.new(mode='RGB', size=(100, 50), color=color_bg) imagedraw = ImageDraw(image, mode='RGB') the_code = get_txt() upper_code = the_code.upper() request.session["the_code"] = upper_code font = ImageFont.truetype("C:\Windows\Fonts\simsunb.ttf", 50) for i in range(4): fill = (get_color(), get_color(), get_color()) imagedraw.text(xy=(25 * i, 0), text=the_code[i], fill=fill, font=font) for i in range(1000): fill = (get_color(), get_color(), get_color()) xy = (random.randrange(201), random.randrange(100)) imagedraw.point(xy=xy, fill=fill) imagedraw.arc( (random.randrange(0, 10), 6, 100, random.randrange(70, 100)), random.randrange(0, 180), random.randrange(250, 360), fill=get_color()) fp = BytesIO() image.save(fp, "png") return HttpResponse(fp.getvalue(), content_type="image/png")
def getcode(request): # 初始化画布,画笔 mode = 'RGB' size = (200, 100) red = get_color() green = get_color() blue = get_color() # 三个 255 背景白色 color_bg = (255, 255, 255) image = Image.new(mode=mode, size=size, color=color_bg) imagedraw = ImageDraw(image, mode=mode) imagefont = ImageFont.truetype(settings.FONT_PASH, 120) verify_code = generate_code() # 验证码内容存储到服务器 request.session['verify_code'] = verify_code for i in range(4): fill = (get_color(), get_color(), get_color(), get_color()) imagedraw.text(xy=(45 * i, 0), text=verify_code[i], font=imagefont, fill=fill) for i in range(1000): fill = (get_color(), get_color(), get_color(), get_color()) xy = (random.randrange(200), random.randrange(100)) imagedraw.point(xy=xy, fill=fill) # imagedraw.line(xy=xy,fill= blue,width=99) fp = BytesIO() image.save(fp, 'png') return HttpResponse(fp.getvalue(), content_type='image/png')
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 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 prepare_rankingur(settings, ur): """ :param settings: Settings :param ur: [error -, error +, ur] :return: """ error_ = "{:.2f}".format(ur[0]) error = "{:.2f}".format(ur[1]) ur = "{:.2f}".format(ur[2]) text = [ "Accuracy:", f"Error {error_}ms - {error}ms avg", f"Unstable Rate: {ur}" ] scale = settings.scale * 1.3 width = int(scale * 350) height = int(width * 9 / 16 * len(text) / 6) image = Image.new("RGBA", (width, height)) d = ImageDraw(image) rounded_rectangle(d, ((0, 0), (width, height)), 20, fill=(255, 255, 255, 200)) rounded_rectangle(d, ((2, 2), (width - 2, height - 2)), 15, fill=(0, 0, 0, 200)) texti = prepare_text(text, scale * 20, (255, 255, 255), settings) y = height * 0.025 for t in texti: imageproc.add(texti[t], image, width * 0.01, y, topleft=True) y += texti[t].size[1] + 5 * settings.scale image = image.resize((width // 2, height // 2)) return [image]
def getCode(request): mode = 'RGB' size = (200,100) red = get_color() green = get_color() blue = get_color() color = (red,green,blue) image = Image.new(mode=mode, size=size, color=color) imagefont = ImageFont.truetype(settings.FONT_PATH,80) imageDraw = ImageDraw(image) verify_code = generate_code() request.session['verify_code'] = verify_code for i in range(4): fill = (get_color(),get_color(),get_color()) imageDraw.text(xy=(50*i, 0), text=verify_code[i], font=imagefont,fill=fill) for i in range(200): fill = (get_color(),get_color(),get_color()) xy = (random.randrange(201),random.randrange(101)) imageDraw.point(xy=xy,fill=fill) fp = BytesIO() image.save(fp,'png') return HttpResponse(fp.getvalue(), content_type='image/png')
def markup(self, i, j, color, opacity): image = self.image rgb = image.convert('RGB') x = ImageDraw(image) # When opacity==0, simplifying the code leads to better performance if opacity == 0: x.point((i, j), fill=color) else: # To mix the colors, I added and dived the RGB values between the current color and the desired one try: pixel = rgb.getpixel((i, j)) except IndexError: return try: index0 = (color[0] * opacity) + (pixel[0] * (100 - opacity)) index1 = (color[1] * opacity) + (pixel[1] * (100 - opacity)) index2 = (color[2] * opacity) + (pixel[2] * (100 - opacity)) x.point((i, j), fill=(int(index0 / 100), int(index1 / 100), int(index2 / 100))) except ZeroDivisionError: pass copied_im = image.copy() copied_im.save('C:\\ShrihanCoding\\PycharmProjectsSourceCode\\.Pong GUI\\Icons\\markup.png')
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 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 __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_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 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 __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 render(self, root_view) -> PILImage.Image: image = PILImage.new(ColorSpace.RGB.value, self.size.xy, Color.clear().rgba) context = RenderContext(origin=Point.zero(), container_size=self.size, draw=ImageDraw(image, mode='RGBA'), color_space=self.color_space) root_view.render(context) return image.convert(self.color_space.value)
def gen_random_color_example(w, h, count, draw_polygon_fns, max_polygons, min_polygons=1): im = Image.new('RGB', (w, h)) grey_im = Image.new('1', (w, h)) draw = ImageDraw(im, 'RGB') grey_draw = ImageDraw(grey_im, '1') for _ in range(randint(min_polygons, max_polygons)): p1, p2 = random_point_pair(w, h) draw_fn = partial(choice(draw_polygon_fns), p1, p2) draw_fn(draw, fill=tuple(randint(0, 255) for _ in range(3))) draw_fn(grey_draw, fill=1) (area, ) = ImageStat.Stat(grey_im).sum total_area = w * h if not count: area /= total_area return (im, area)
def gen_binary_example(w, h, count, draw_polygon_fn, num_polygons=1): example = Image.new("1", (w, h)) draw = ImageDraw(example, mode="1") for i in range(num_polygons): draw_polygon_fn(w, h, draw) (area, ) = ImageStat.Stat(example).sum total_area = w * h if not count: area /= total_area return (example, area)
def draw_bounding_boxes(image_path, merged_detection_results): image = Image.open(image_path) # type: Image.Image image = image.convert("RGB") image_draw = ImageDraw(image) for i, row in merged_detection_results.iterrows(): color = STANDARD_COLORS[classes[row["class_name"]] % len(STANDARD_COLORS)] image_draw.rectangle( [row["left"], row["top"], row["right"], row["bottom"]], outline=color, width=4) image.save(image_path.replace(".png", "_detection.png"))
def selective_search(original): data = tf.keras.preprocessing.image.img_to_array(original) ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() ss.setBaseImage(data) ss.switchToSelectiveSearchFast() # ss.switchToSelectiveSearchQuality() boxes = ss.process() draw = ImageDraw(original) print("found") for box in boxes: draw.rectangle(list(box), outline="#00f000", width=2) return original
def to_image(self): a = np.zeros((self._height, self._width), dtype=np.uint8) im = Image.fromarray(a, mode='L') canvas = ImageDraw(im, mode='L') for x, y, prev_point in self.points_generator(): if prev_point: canvas.line((prev_point, (x, y)), width=12, fill=255) return im
def procesar_disenio(idDisenio): print 'Entra a procesar disenio' disenio = Connection.db.disenios.find_one({'_id': ObjectId(idDisenio)}) 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 get_code(request): mode = 'RGB' size = (200, 100) red = get_color() green = get_color() blue = get_color() # 随机画布的背景颜色 color_bg = (red, green, blue) # 构造画布 image = Image.new(mode=mode, size=size, color=color_bg) # 初始化画笔 imagedraw =ImageDraw(image, mode=mode) # 设置字体和字体大小 imagefont = ImageFont.truetype(settings.FONT_PATH, 100) verify_code = generate_verification_code() # 通过session记录这个验证码并且设置过期时间为60秒 request.session['verifycode'] = verify_code request.session.set_expiry(20) # 随机每个验证码的颜色 for i in range(4): # 随机颜色 fill = (get_color(),get_color(),get_color()) imagedraw.text(xy=(50*i, 0), text=verify_code[i], font=imagefont,fill=fill) # 生成验证码图片上的干扰点 for i in range(1000): # 随机颜色 fill = (get_color(), get_color(), get_color()) # xy的随机坐标和画布的大小size一样 也就是画布整体都加干扰点 xy = (random.randrange(201),random.randrange(100)) imagedraw.point(xy=xy, fill=fill) # 生成验证码图片上的干扰线 for i in range(5): # 随机颜色 fill = (get_color(), get_color(), get_color()) # xy的随机坐标和画布的大小size一样 也就是画布整体都加干扰点 x1 = (random.randrange(200)) x2 = (random.randrange(200)) y1 = (random.randrange(100)) y2 = (random.randrange(100)) imagedraw.line(xy=(x1,y1,x2,y2),fill=fill,width=2) # 内存流 fp = BytesIO() # 将验证码图片存在内存流中 image.save(fp, 'png') return HttpResponse(fp.getvalue(), content_type='image/png')
def draw_map(test_img, pix_map_normlized, outline=None): if outline is None: outline = (0, 0, 0) draw_api = ImageDraw(test_img) for pixel in pix_map_normlized: coordinate_from = ( int(pixel[0] * IMG_SIZE) - DOT_RADIUS, int(pixel[1] * IMG_SIZE) - DOT_RADIUS ) coordinate_to = ( int(pixel[0] * IMG_SIZE) + DOT_RADIUS, int(pixel[1] * IMG_SIZE) + DOT_RADIUS ) draw_api.ellipse([coordinate_from, coordinate_to], outline=outline)