def make_check_code_image(self, image=''): color = ImageColor.getrgb('white') #im = Image.open(image) im = Image.new('RGB',(60,20), color) draw = ImageDraw.Draw(im) mp = md5.new() mp_src = mp.update(str(datetime.datetime.now())) mp_src = mp.hexdigest() rand_str = mp_src[0:4] #print rand_str color = ImageColor.getrgb('LightGray') for i in range(200): x = random.randrange(1,60) y = random.randrange(1,20) draw.point((x, y), fill=color) draw.text((5, 1), rand_str[0], fill = self.get_color(), font = self.get_font()) draw.text((15, 1), rand_str[1], fill = self.get_color(), font = self.get_font()) draw.text((30, 1), rand_str[2], fill = self.get_color(), font = self.get_font()) draw.text((45, 1), rand_str[3], fill = self.get_color(), font = self.get_font()) draw.line((0, 10, 60, 15), fill = self.get_color()) del draw session['checkcode'] = rand_str buf = StringIO.StringIO() im.save(buf, 'gif') buf.closed if image: im.save(image) return buf.getvalue()
def colorize(data, colormap): #data = np.zeros((256, 256), dtype=np.float32) #data.data = raw.data out = np.zeros((256, 256, 4), dtype=np.uint8) tmp = np.zeros((256, 256), dtype=np.uint32) tmp.data = out.data c = np.zeros(4, dtype=np.uint8) d = np.zeros(1, dtype=np.uint32) d.data = c.data if colormap['missing']: c[0:3] = ImageColor.getrgb(colormap['missing']) else: c[0:3] = 0 c[3] = 255 tmp[...] = d n = 0 for b in colormap['bounds']: step = 1.0*(b['end'] - b['start'])/b['steps'] for i in range(b['steps']): low = b['start'] + i*step high = low + step mask = np.logical_and(data > low, data < high) c[0:3] = ImageColor.getrgb(colormap['colors'][n + i]) tmp[mask] = d n += b['steps'] return out
def draw_baselines(self, img_in): img_out = img_in.copy() draw = ImageDraw.Draw(img_out) prev_floor = 0 w, h = img_out.size gap_color = ImageColor.getrgb('#ccccFF') lines = scrape.calc_lines(scrape.font_metrics(), 7) for i, (ceiling, base, floor) in enumerate(lines): # draw the baseline color = ImageColor.getrgb("#ffdddd") if not base: base = floor -2 color = ImageColor.getrgb("red") draw.line([(0, base), (w, base)], fill=color) # shade gap between the lines draw.rectangle((0, prev_floor, w, ceiling), fill=gap_color) prev_floor = floor +1 # shade final gap: draw.rectangle((0, prev_floor, w, h), fill=gap_color) # now draw the text back over the baselines: img_out = ImageChops.darker(img_in, img_out) # uncomment to zoom in for debugging # img_out = img_out.resize((w *2 , h* 2)) return img_out
def main(): global back, couleurs, grids, thumbs #----- Main code ------------------------ console.clear() grids = [ '1', '12', '1/2', '123', '11/23', '12/33', '1/2/3', '12/32', '12/13', '1234', '111/234', '12/34', '123/444', '11/22/34', '12/33/44', '11/23/44', '1/2/3/4', '12/13/14', '12/32/42', '11/23/43', '123/143', '123/425', '1234/5678/9abc/defg', '12345/67890/abcde/fghij/klmno' ] #, '5', '1/4', '4/1', '2/3', f'3/2', '1/1/3', '1/3/1', '2/1/2', '2/2/1', '1/2/2', '3/1/1','1/1/1/2', '1/1/2/1', '1/2/1/1', '2/1/1/1', '1/1/1/1/1'] couleurs = [ 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen', 'black', 'blue', 'blueviolet', 'brown', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet' ] # Sort colors on HSL H=Hue(teinte) S=Saturation L=Lightness(luminosité) couleurs = sorted(couleurs, key=lambda x: colorsys.rgb_to_hsv( ImageColor.getrgb(x)[0], ImageColor.getrgb(x)[1], ImageColor.getrgb(x)[2])) w, h = ui.get_screen_size() disp = 'full_screen' back = MyView(w, h) back.background_color = 'white' back.present(disp, hide_title_bar=True) thumbs = {}
def init(self, color=ImageColor.getrgb('white'), decor_color=ImageColor.getrgb('blue')): self.color = color self.pillow = Decor(Rect(1, 1, 2, 1), self, 'pillow') self.pillow.color = decor_color self.sheet = Decor(Rect(0, 3, 4, 5), self, 'sheet') self.sheet.color = decor_color
def writeProgressImage(value, range, file, text=None, warnThreshold=0.8): import PIL import Image, ImageDraw, ImageColor, ImageFont WIDTH = 100 HEIGHT = 18 def centerTextInBox(font, text, size): center = [0, 0] center[0] = size[0] / 2.0 - font.getsize(text)[0] / 2.0 center[1] = size[1] / 2.0 - font.getsize(text)[1] / 2.0 + 1 return center im = Image.new("RGBA", (WIDTH, HEIGHT)) outline = ImageColor.getrgb("#000000") background = ImageColor.getrgb("#4697ff") bar = ImageColor.getrgb("#14ff00") barWarn = ImageColor.getrgb("#ff0f00") textColour = ImageColor.getrgb("#000000") try: percentage = float(value) / range except: percentage = 0.0 if percentage > warnThreshold: barColour = barWarn else: barColour = bar barWidth = percentage * im.size[0] barWidth = min(barWidth, im.size[0]) draw = ImageDraw.Draw(im) draw.rectangle([0, 0, im.size[0] - 1, im.size[1] - 1], outline=outline, fill=background) draw.rectangle([0, 0, barWidth - 1, im.size[1] - 1], outline=outline, fill=barColour) font = ImageFont.load_default() try: font = ImageFont.truetype("/var/tmp/Nimbus Sans L,", 16) except: debugOutput("Cannot load Nimbus font") font = ImageFont.load_default() if text: draw.text(centerTextInBox(font, text, im.size), text, font=font, fill=textColour) if not drool.settings.options.testRun: im.save(file)
def genImage(self): """Create a PNG from the contents of this flowable. Required so we can put inline math in paragraphs. Returns the file name. The file is caller's responsability. """ dpi = 72 scale = 10 try: import Image import ImageFont import ImageDraw import ImageColor except ImportError: from PIL import ( Image, ImageFont, ImageDraw, ImageColor, ) if not HAS_MATPLOTLIB: img = Image.new('L', (120, 120), ImageColor.getcolor("black", "L")) else: width, height, descent, glyphs,\ rects, used_characters = self.parser.parse( enclose(self.s), dpi) img = Image.new('L', (int(width*scale), int(height*scale)), ImageColor.getcolor("white", "L")) draw = ImageDraw.Draw(img) for ox, oy, fontname, fontsize, num, symbol_name in glyphs: font = ImageFont.truetype(fontname, int(fontsize*scale)) tw, th = draw.textsize(unichr(num), font=font) # No, I don't understand why that 4 is there. # As we used to say in the pure math # department, that was a numerical solution. draw.text((ox*scale, (height - oy - fontsize + 4)*scale), unichr(num), font=font) for ox, oy, w, h in rects: x1 = ox*scale x2 = x1 + w*scale y1 = (height - oy)*scale y2 = y1 + h*scale draw.rectangle([x1, y1, x2, y2], fill=ImageColor.getcolor("black", "L")) fh, fn = tempfile.mkstemp(suffix=".png") os.close(fh) img.save(fn) return fn
def general_filling_rec(fillcolor, bordercolor, maxX, maxY, draw, pic, x, y): sys.setrecursionlimit(100000) fc = ImageColor.getrgb(fillcolor) bc = ImageColor.getrgb(bordercolor) def GFill(x, y): if 0 < x < maxX and 0 < y < maxY: color = pic.getpixel((x, y)) if color != bc and color != fc: draw.point([x, y], fc) GFill(x + 1, y) GFill(x, y + 1) GFill(x - 1, y) GFill(x, y - 1)
def create_cluster_colors_rgb(n, normalize=True): # create n distinct colors in rgb format colors = [] for i in range(n): h = int( float(i) / float(n) * 360.0 ) s = 50 l = 50 if normalize: colors.append(np.array(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h,s,l))) / 255.0 ) else: colors.append(np.array(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h,s,l)))) return colors
def writeProgressImage(value, range, file, text=None, warnThreshold=0.8) : import PIL import Image, ImageDraw, ImageColor, ImageFont WIDTH = 100 HEIGHT = 18 def centerTextInBox(font, text, size) : center = [0,0] center[0] = size[0]/2.0 - font.getsize(text)[0]/2.0 center[1] = size[1]/2.0 - font.getsize(text)[1]/2.0 + 1 return center im = Image.new("RGBA",(WIDTH, HEIGHT)) outline = ImageColor.getrgb("#000000") background = ImageColor.getrgb("#4697ff") bar = ImageColor.getrgb("#14ff00") barWarn = ImageColor.getrgb("#ff0f00") textColour = ImageColor.getrgb("#000000") try : percentage = float(value)/range except : percentage = 0.0 if percentage > warnThreshold : barColour = barWarn else : barColour = bar barWidth = percentage * im.size[0] barWidth = min(barWidth, im.size[0]) draw = ImageDraw.Draw(im) draw.rectangle([0,0, im.size[0]-1, im.size[1]-1], outline=outline, fill=background) draw.rectangle([0,0, barWidth-1, im.size[1]-1], outline=outline, fill=barColour) font = ImageFont.load_default() try : font = ImageFont.truetype("/var/tmp/Nimbus Sans L,",16) except : debugOutput("Cannot load Nimbus font") font = ImageFont.load_default() if text : draw.text(centerTextInBox(font, text, im.size), text, font=font, fill=textColour) if not drool.settings.options.testRun : im.save(file)
def drawSkin(imagePath, size, outlineColour, bgColour) : import PIL import Image, ImageDraw, ImageColor, ImageFont borderWidth = 2 im = Image.new("RGBA",(size[0], size[1])) outline = ImageColor.getrgb(outlineColour) background = ImageColor.getrgb(bgColour) draw = ImageDraw.Draw(im) draw.rectangle([0,0, im.size[0]-1, im.size[1]-1], outline=outline, fill=background) im.save(imagePath)
def setink(self, ink): # compatibility if Image.isStringType(ink): ink = ImageColor.getcolor(ink, self.mode) if self.palette and not Image.isNumberType(ink): ink = self.palette.getcolor(ink) self.ink = self.draw.draw_ink(ink, self.mode)
def display_distance_LUT(self, dlut, sname): display_im = self.im.copy() draw = ImageDraw.Draw(display_im) max_d = 0 for gx in range(self.grid_width - 1): for gy in range(self.grid_height - 1): (x, y) = self.grid_to_map((gx, gy)) if (gx, gy) in self.occupied: continue min_d = 40.0 for ga in range(self.num_angles - 1): d = dlut.distance(x, y, self.discrete_angle_to_map_angle(ga)) if d < min_d: min_d = d if min_d > max_d: max_d = min_d rvalue = int(255 - (min_d * 255 / 5.0)) if rvalue < 0: rvalue = 0 self.draw_grid_rectangle( gx, gy, draw, ImageColor.getrgb('rgb(' + str(rvalue) + ',0,0)')) #Save the image display_im.save(sname) del draw del display_im
def ent2img(visited_tab, m): global red target_px_w = 640 target_px_h = 480 target_px = target_px_w * target_px_h target_dim = (target_px_w, target_px_h) m.write() # only care about coverage for regions that are exec if not m.is_exec(): return None # ignore empty regions, if any if m.end - m.begin == 0: return None pixels_per_byte = float(target_px) / float(m.end - m.begin) if pixels_per_byte == 0: print "0 pixels per byte. Whoops" return None im = Image.new("RGB", target_dim, ImageColor.getrgb("black")) for (k, num_bytes) in visited_tab.items(): if k < m.begin or k + num_bytes > m.end: continue offset = int(pixels_per_byte * (k - m.begin)) for i in range(0, int(num_bytes * pixels_per_byte)): x = (offset + i) % target_px_w y = (offset + i) / target_px_w im.putpixel((x, y), red) return im
def color_bg(request, color, opacity=100): """ Generates a 10x10 square image in the color requested. Useful for generating background colors based on user-provided color settings. """ import Image, ImageDraw, ImageColor alpha = int((int(opacity) / 100.0) * 255) if len(color) != 3 and len(color) != 6: raise Http404 color = "#%s" % color color = ImageColor.getrgb(color) + (alpha,) size = (10, 10) etag = md5_constructor("%s%s" % (color, size)).hexdigest() if request.META.get("HTTP_IF_NONE_MATCH") == etag: return HttpResponseNotModified() img = Image.new("RGBA", size=size, color=color) response = HttpResponse(mimetype="image/png") img.save(response, "PNG") response["Etag"] = etag return response
def assignMatPlotlibHueColorToLs(name_ls, debug=0): """ 2008-10-07 assign continuous HSL color spectrum to a list (in order). """ if debug: sys.stderr.write("Assigning matplotlib hue color to a list ...") import ImageColor no_of_names = len(name_ls) value_step = 1. / (no_of_names - 1 ) #-1 to cover both minimum and maximum in the spectrum name2fc = {} for i in range(no_of_names): name = name_ls[i] value = i * value_step hue_value = max(min(int(round((1 - value) * 255)), 255), 0) #max(min()) makes sure it's 0-255 fc = ImageColor.getrgb( 'hsl(%s' % hue_value + ',100%,50%)' ) #"hsl(hue, saturation%, lightness%)" where hue is the colour given as an # angle between 0 and 360 (red=0, green=120, blue=240), #saturation is a value between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%, normal=50%, white=100%). fc = [color_value / 255. for color_value in fc] #matplotlib accepts rgb in [0-1] range name2fc[name] = fc if debug: sys.stderr.write("Done.\n") return name2fc
def pt2color(self, map, pt, max): v = self.mapget(map, pt) c = 100 - min(v, max) * 100 / max h = 3.6 * c return ImageColor.getcolor( 'hsl(' + str(int(h)) + ',' + str(c) + '%,' + str(c) + '%)', 'RGB')
def display_distance_LUT(self, dlut, sname): display_im = self.im.copy() draw = ImageDraw.Draw(display_im) print 'Grid w x h =', self.grid_width, self.grid_height max_d = 0 for gx in range(self.grid_width-1): for gy in range(self.grid_height-1): (x,y) = self.grid_to_map((gx,gy)) if (gx,gy) in self.occupied: continue min_d = 40.0 for ga in range(self.num_angles-1): #print d = dlut.distance(x,y,self.discrete_angle_to_map_angle(ga)) #d2 = self.distance_to_obstacle((gx,gy),self.discrete_angle_to_map_angle(ga)) #print 'Checking <', gx, gy, ga, '> d = ', d, 'd2=',d2 if d < min_d: min_d = d #print (x,y), '->', min_d if min_d > max_d: max_d = min_d rvalue = int(255 - (min_d*255/5.0)) if rvalue < 0: rvalue = 0 self.draw_grid_rectangle(gx,gy,draw,ImageColor.getrgb('rgb(' + str(rvalue) + ',0,0)')) print 'MAX D= ', max_d #Save the image display_im.save(sname) del draw del display_im
def run(self): self._d24.debug('Running!') orig = Image.open("unpacked/%s.jpg" % self._name) draw = ImageDraw.Draw(orig) size = orig.size res = Image.open("unpacked/%s-act.jpg" % self._name) while not self.stopit: for r, row in enumerate(self._piece): for c, cell in enumerate(row): if not cell[2]: continue im = Image.open("unpacked/%s/%s-%d-%d.jpg" % (self._name, self._name, r + 1, c + 1)) cwidth, cheight = im.size im = im.rotate(rotator[cell[3]]) res.paste(im, (cell[1] * cwidth, cell[0] * cheight, (cell[1] + 1) * cwidth, (cell[0] + 1) * cheight)) draw.rectangle(((c * cwidth, r * cheight), ((c + 1) * cwidth, (r + 1) * cheight)), ImageColor.getcolor('black', 'RGB')) res.save("unpacked/%s-act.jpg" % self._name) orig.save("unpacked/%s.jpg" % self._name) self._d24.debug('Drawed') time.sleep(2) self._d24.debug('Closed!')
def brightness(image, amount=50): """Adjust brightness from black to white - amount: -1(black) 0 (unchanged) 1(white) - repeat: how many times it should be repeated""" if amount == 0: return image image = imtools.convert_safe_mode(image) if amount < 0: #fade to black im = imtools.blend( image, Image.new(image.mode, image.size, 0), -amount / 100.0) else: #fade to white im = imtools.blend( image, Image.new(image.mode, image.size, ImageColor.getcolor('white', image.mode)), amount / 100.0) #fix image transparency mask if imtools.has_alpha(image): im.putalpha(imtools.get_alpha(image)) return im
def crop(image_file, bgcolor=ImageColor.getrgb("white")): image = Image.open(image_file,'r') mask = Image.new("RGB", image.size, bgcolor) diff = ImageChops.difference(image, mask) bbox = diff.getbbox() new_image = image.crop(bbox) new_image.save(image_file,"png")
def genImage(self): """Create a PNG from the contents of this flowable. Required so we can put inline math in paragraphs. Returns the file name. The file is caller's responsability. """ dpi = 72 scale = 10 import Image import ImageFont import ImageDraw import ImageColor if not HAS_MATPLOTLIB: img = Image.new('L', (120, 120), ImageColor.getcolor("black", "L")) else: width, height, descent, glyphs,\ rects, used_characters = self.parser.parse( '$%s$' % self.s, dpi) img = Image.new('L', (int(width * scale), int(height * scale)), ImageColor.getcolor("white", "L")) draw = ImageDraw.Draw(img) for ox, oy, fontname, fontsize, num, symbol_name in glyphs: font = ImageFont.truetype(fontname, int(fontsize * scale)) tw, th = draw.textsize(unichr(num), font=font) # No, I don't understand why that 4 is there. # As we used to say in the pure math # department, that was a numerical solution. draw.text((ox * scale, (height - oy - fontsize + 4) * scale), unichr(num), font=font) for ox, oy, w, h in rects: x1 = ox * scale x2 = x1 + w * scale y1 = (height - oy) * scale y2 = y1 + h * scale draw.rectangle([x1, y1, x2, y2], fill=ImageColor.getcolor("black", "L")) fh, fn = tempfile.mkstemp(suffix=".png") os.close(fh) img.save(fn) return fn
def __init__(self, fontname, textcol_bright, textcol_dark, textsize=40, noiselines=False, bgpicture=None, squiggly=False): self.font=ImageFont.truetype(fontname, textsize) self.lettersize=self.font.getsize('x') if type(textcol_bright)!=tuple: textcol_bright=ImageColor.getrgb(textcol_bright) if type(textcol_dark)!=tuple: textcol_dark=ImageColor.getrgb(textcol_dark) self.textcol_bright=textcol_bright self.textcol_dark=textcol_dark ar,ag,ab=self.textcol_bright self.textcol_avg=(ar+self.textcol_dark[0])/2, (ag+self.textcol_dark[1])/2, (ab+self.textcol_dark[2])/2 self.noiselines=noiselines self.squiggly=squiggly if bgpicture: self.bgpicture=Image.open(bgpicture) else: self.bgpicture=None
def create_cluster_colors_rgb(n, normalize=True): # create n distinct colors in rgb format colors = [] for i in range(n): h = int(float(i) / float(n) * 360.0) s = 50 l = 50 if normalize: colors.append( np.array(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h, s, l))) / 255.0) else: colors.append( np.array(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h, s, l)))) return colors
def drawSkin(imagePath, size, outlineColour, bgColour): import PIL import Image, ImageDraw, ImageColor, ImageFont borderWidth = 2 im = Image.new("RGBA", (size[0], size[1])) outline = ImageColor.getrgb(outlineColour) background = ImageColor.getrgb(bgColour) draw = ImageDraw.Draw(im) draw.rectangle([0, 0, im.size[0] - 1, im.size[1] - 1], outline=outline, fill=background) im.save(imagePath)
def double_ended(low, zero, high, *args, **kwargs): '''double_ended(low, zero, high) -> ColorMap low, zero, high should be scalar. Returns a ColorMap that is grey at zero and increases in saturation toward low and high.''' lowcolor = ImageColor.getrgb("hsl(180,100%,50%)") highcolor = ImageColor.getrgb("hsl(0,100%,50%)") zerocolor = ImageColor.getrgb("hsl(0,100%,0%)") points = np.asarray([ (low,) + lowcolor, (zero,) + zerocolor, (high,) + highcolor ]) return ColorMap(points)
def setink(self, ink): # compatibility if warnings: warnings.warn("'setink' is deprecated; use keyword arguments instead", DeprecationWarning, stacklevel=2) if Image.isStringType(ink): ink = ImageColor.getcolor(ink, self.mode) if self.palette and not Image.isNumberType(ink): ink = self.palette.getcolor(ink) self.ink = self.draw.draw_ink(ink, self.mode)
def return_rgb_color_given_score(self, score, value2color_func): """ 2008-11-15 """ hue_value_in_hsl_format = value2color_func(score) fc = ImageColor.getrgb(hue_value_in_hsl_format) #"hsl(hue, saturation%, lightness%)" where hue is the colour given as an # angle between 0 and 360 (red=0, green=120, blue=240), #saturation is a value between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%, normal=50%, white=100%). fc = [color_value/255. for color_value in fc] return fc
def create_cluster_colors(n): # create n distinct colors in rgb format colors = [] for i in range(n): h = int( float(i) / float(n) * 360.0 ) s = 50 l = 50 colors.append(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h,s,l)) ) return colors
def _getink(self, ink, fill=None): if ink is None and fill is None: if self.fill: fill = self.ink else: ink = self.ink else: if ink is not None: if Image.isStringType(ink): ink = ImageColor.getcolor(ink, self.mode) if self.palette and not Image.isNumberType(ink): ink = self.palette.getcolor(ink) ink = self.draw.draw_ink(ink, self.mode) if fill is not None: if Image.isStringType(fill): fill = ImageColor.getcolor(fill, self.mode) if self.palette and not Image.isNumberType(fill): fill = self.palette.getcolor(fill) fill = self.draw.draw_ink(fill, self.mode) return ink, fill
def create_cluster_colors(n): # create n distinct colors in rgb format colors = [] for i in range(n): h = int(float(i) / float(n) * 360.0) s = 50 l = 50 colors.append(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h, s, l))) return colors
def setink(self, ink): # compatibility if warnings: warnings.warn( "'setink' is deprecated; use keyword arguments instead", DeprecationWarning) if Image.isStringType(ink): ink = ImageColor.getcolor(ink, self.mode) if self.palette and not Image.isNumberType(ink): ink = self.palette.getcolor(ink) self.ink = self.draw.draw_ink(ink, self.mode)
def get_ink_with_alpha(self, fill=None, alpha=None): ink = self.ink if (fill == None) else fill if ink == None: return ink if Image.isStringType(ink): ink = ImageColor.getcolor(ink, self.mode) if self.palette and not Image.isNumberType(ink): ink = self.palette.getcolor(ink) if alpha != None: #and self.mode == "RGBA" ink = ink[:3]+(alpha,) #print ink return self.draw.draw_ink(ink, self.mode)
def get_ink_with_alpha(self, fill=None, alpha=None): ink = self.ink if (fill == None) else fill if ink == None: return ink if Image.isStringType(ink): ink = ImageColor.getcolor(ink, self.mode) if self.palette and not Image.isNumberType(ink): ink = self.palette.getcolor(ink) if alpha != None: #and self.mode == "RGBA" ink = ink[:3] + (alpha, ) #print ink return self.draw.draw_ink(ink, self.mode)
def return_rgb_color_given_score(self, score, value2color_func): """ 2008-11-15 """ hue_value_in_hsl_format = value2color_func(score) fc = ImageColor.getrgb( hue_value_in_hsl_format ) #"hsl(hue, saturation%, lightness%)" where hue is the colour given as an # angle between 0 and 360 (red=0, green=120, blue=240), #saturation is a value between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%, normal=50%, white=100%). fc = [color_value / 255. for color_value in fc] return fc
def __init__(self, colormap, background=None, background_image=None): '''Each argument to the constructor should be a 4-tuple of (hue, saturaton, value, alpha), one to use for minimum data values and one for maximum. Each should be in [0,1], however because hue is circular, you may specify hue in any range and it will be shifted into [0,1] as needed. This is so you can wrap around the color wheel in either direction.''' self.colormap = colormap self.background_image = background_image self.background = None if background and not background_image: self.background = ImageColor.getrgb(background)
def build_tree(): tree = Quad(Rect(0, 0, size, size)) level = Level(Rect(0, 0, size, size)) level.color = ImageColor.getcolor('grey', mode) tree.charge(level) room = Room(Rect(4, 4, 16, 16), level, name='room') room.color = ImageColor.getcolor('orange', mode) tree.charge(room) table = Furniture(Rect(0, 0, 4, 3), room, name='table') table.color = ImageColor.getcolor('brown', mode) lamp = Furniture(Rect(1, 1, 1, 1), table, name='lamp') lamp.color = ImageColor.getcolor('yellow', mode) tree.charge(table) bed = Bed(Rect(4, 0, 4, 8), room, color=ImageColor.getrgb('white'), decor_color=ImageColor.getrgb('darkcyan')) tree.charge(bed) bed2 = Bed(Rect(9, 0, 4, 8), room, color=ImageColor.getrgb('white'), decor_color=ImageColor.getrgb('crimson')) tree.charge(bed2) bed2.tear_down() #bed = Furniture(Rect(4, 0, 4, 8), room, name='bed') #bed.color = ImageColor.getcolor('green', mode) #tree.charge(bed) #pillow = Furniture(Rect(1, 1, 2, 1), bed, name='pillow') #pillow.color = ImageColor.getcolor('white', mode) #tree.charge(pillow) #sheet = Furniture(Rect(0, 3, 4, 5), bed, name='sheet') #sheet.color = ImageColor.getcolor('white', mode) #tree.charge(sheet) lump = Block(Rect(32, 32, 8, 8), room, name='lump', abs=True) lump.color = ImageColor.getcolor('black', mode) tree.charge(lump) return tree
def build_and_print_matrices_deg_colored(v,strat): """old PIL solution using a different color for each degree""" if len(v)==0: return treated=BooleSet() v=list(v) rows=0 polys_in_mat=[] while(len(v)>0): rows=rows+1 p=v[0] v=v[1:] for m in list(p.terms()): m=Monomial(m) if not m in BooleSet(treated): i=strat.select(m) if i>=0: p2=strat[i] p2=p2*(m//p2.lead()) v.append(p2) polys_in_mat.append(p) treated=treated.union(p.set()) m2i=dict([(v,k) for (k,v) in enumerate(BooleSet(treated))]) max_deg=max([m.deg() for m in BooleSet(treated)]) if max_deg==0: max_deg=1 i2deg=dict([(m2i[m],m.deg()) for m in BooleSet(treated)]) polys_in_mat=[[m2i[t] for t in p.terms()] for p in polys_in_mat] polys_in_mat.sort(key=pkey) global mat_counter mat_counter=mat_counter+1 import Image, ImageDraw, ImageColor rows=len(polys_in_mat) cols=len(m2i) im=Image.new("RGB",(cols,rows),"white") for i in xrange(len(polys_in_mat)): p=polys_in_mat[i] for j in p: assert i<rows assert j<cols im.putpixel((j,i), ImageColor.getrgb("hsl("+str(270-(270*i2deg[j])/max_deg)+",100%,50%)")) file_name=matrix_prefix+str(mat_counter)+".png" import os os.system("rm -f file_name") im.save(file_name) del im print "MATRIX_SIZE:", rows,"x",cols
def render(self, im, bgcolor="#FFFFFF", amount=0.4, opacity=0.6): """ Returns the supplied PIL Image (im) with a reflection effect bgcolor The background color of the reflection gradient amount The height of the reflection as a percentage of the orignal image opacity The initial opacity of the reflection gradient Originally written for the Photologue image management system for Django and Based on the original concept by Bernd Schlapsi """ print "reflection filter" # convert bgcolor string to rgb value background_color = ImageColor.getrgb(bgcolor) # copy orignial image and flip the orientation reflection = im.copy().transpose(Image.FLIP_TOP_BOTTOM) # create a new image filled with the bgcolor the same size background = Image.new("RGB", im.size, background_color) # calculate our alpha mask start = int(255 - (255 * opacity)) # The start of our gradient steps = int(255 * amount) # the number of intermedite values increment = (255 - start) / float(steps) mask = Image.new('L', (1, 255)) for y in range(255): if y < steps: val = int(y * increment + start) else: val = 255 mask.putpixel((0, y), val) alpha_mask = mask.resize(im.size) # merge the reflection onto our background color using the alpha mask reflection = Image.composite(background, reflection, alpha_mask) # crop the reflection reflection_height = int(im.size[1] * amount) reflection = reflection.crop((0, 0, im.size[0], reflection_height)) # create new image sized to hold both the original image and the reflection composite = Image.new("RGB", (im.size[0], im.size[1]+reflection_height), background_color) # paste the orignal image and the reflection into the composite image composite.paste(im, (0, 0)) composite.paste(reflection, (0, im.size[1])) # return the image complete with reflection effect return composite
def add_reflection(im, bgcolor="#00000", amount=0.4, opacity=0.6): """ Returns the supplied PIL Image (im) with a reflection effect bgcolor The background color of the reflection gradient amount The height of the reflection as a percentage of the orignal image opacity The initial opacity of the reflection gradient Originally written for the Photologue image management system for Django and Based on the original concept by Bernd Schlapsi """ # convert bgcolor string to rgb value background_color = ImageColor.getrgb(bgcolor) # copy orignial image and flip the orientation reflection = im.copy().transpose(Image.FLIP_TOP_BOTTOM) # create a new image filled with the bgcolor the same size background = Image.new("RGB", im.size, background_color) # calculate our alpha mask start = int(255 - (255 * opacity)) # The start of our gradient steps = int(255 * amount) # the number of intermedite values increment = (255 - start) / float(steps) mask = Image.new('L', (1, 255)) for y in range(255): if y < steps: val = int(y * increment + start) else: val = 255 mask.putpixel((0, y), val) alpha_mask = mask.resize(im.size) # merge the reflection onto our background color using the alpha mask reflection = Image.composite(background, reflection, alpha_mask) # crop the reflection reflection_height = int(im.size[1] * amount) reflection = reflection.crop((0, 0, im.size[0], reflection_height)) # create new image sized to hold both the original image and the reflection composite = Image.new("RGB", (im.size[0], im.size[1] + reflection_height), background_color) # paste the orignal image and the reflection into the composite image composite.paste(im, (0, 0)) composite.paste(reflection, (0, im.size[1])) # return the image complete with reflection effect return composite
def __init__(self, mode='RGBA', size=(320, 240), background_color=(255, 255, 255)): Image.Image.__init__(self) if background_color == None: im = Image.core.new(mode, size) else: color_type = type(background_color).__name__ if color_type == 'str' or color_type == 'unicode': background_color = ImageColor.getcolor(background_color, mode) im = Image.core.fill(mode, size, background_color) self.im = im self.mode = im.mode self.size = im.size if im.mode == 'P': self.palette = ImagePalette.ImagePalette()
def render_vector(geometry, img, bbox, coords, srs, color=None, renderer=None): """ Renders a vector geometry on image. """ if not color: color = config.geometry_color[geometry] if not renderer: renderer = config.default_vector_renderer bbox = projections.from4326(bbox, srs) lo1, la1, lo2, la2 = bbox coords = projections.from4326(coords, srs) W,H = img.size prevcoord = False coords = [((coord[0]-lo1)*(W-1)/abs(lo2-lo1), (la2-coord[1])*(H-1)/(la2-la1)) for coord in coords] if renderer == "cairo" and HAVE_CAIRO: "rendering as cairo" imgd = img.tostring() a = array.array('B',imgd) surface = cairo.ImageSurface.create_for_data (a, cairo.FORMAT_ARGB32, W, H, W*4) cr = cairo.Context(surface) cr.move_to(*coords[0]) color = ImageColor.getrgb(color) cr.set_source_rgba(color[2], color[1], color[0], 1) if geometry == "LINESTRING" or geometry == "POLYGON": for k in coords: cr.line_to(*k) if geometry == "LINESTRING": cr.stroke() elif geometry == "POLYGON": cr.fill() elif geometry == "POINT": cr.arc(coords[0][0],coords[0][1],6,0,2*math.pi) cr.fill() img = Image.frombuffer("RGBA",( W,H ),surface.get_data(),"raw","RGBA",0,1) else: "falling back to PIL" coord = [(int(coord[0]),int(coord[1])) for coord in coords] # PIL dislikes subpixels draw = ImageDraw.Draw(img) if geometry == "LINESTRING": draw.line (coords, fill=color, width=3) elif geometry == "POINT": draw.ellipse((coords[0][0]-3,coords[0][1]-3,coords[0][0]+3,coords[0][1]+3),fill=color,outline=color) elif geometry == "POLYGON": draw.polygon(coords, fill=color, outline=color) return img
def linear_lum_hue(low, high, *args, **kwargs): '''linear_lum_hue(low, high) -> ColorMap returns a ColorMap that starts with 25% luminosity and blue at low and increases linearly in luminosity and hue to 75% and red at high. A better colormap would walk through the hues in some way that compensates for the fact that hues have different widths on a linear ramp---e.g., a large swath looks green. ''' n = 10 points = [ (val,) + col for val, col in zip(*[ np.linspace(low, high, num=n), [ ImageColor.getrgb("hsl(%d,100%%,%d%%)" % (c % 360, l)) for c,l in zip(np.linspace(350,600,num=n), np.linspace(60,25,num=n)) ][::-1] ]) ] return ColorMap(np.asarray(points))
def ppng(f, names, matrix, nodes, classifier, coloration, signature, outFileName, opt): import Image, ImageColor zoom = 2 steps = classifier(matrix) colors = coloration(0, 1., steps, get_color_html) l = len(nodes) h = l * zoom image = Image.new("RGBA", (h, h)) for i, n in enumerate(nodes): for j in xrange(l): cls, c = get_color(matrix[(i, j)], steps, colors) for k1 in xrange(zoom) : for k2 in xrange(zoom) : rgba = ImageColor.getcolor(c, "RGBA") image.putpixel((i*zoom+k1, j*zoom+k2), rgba) image.save(f,"png")
def textfield_did_change(self, textfield): if textfield.text == '': textfield.text = '#' elif '##' in textfield.text: textfield.text = textfield.text.replace('##', '#') elif len(textfield.text) == 7: rgb = ImageColor.getrgb(textfield.text) r, g, b = rgb v = textfield.superview['groupView'] v['slider1'].value = float(r) / 255 v['slider2'].value = float(g) / 255 v['slider3'].value = float(b) / 255 v.superview.slider_action(v['slider1']) pass
def test(): scaled = size*scale im = Image.new( mode, (scaled, scaled), color=ImageColor.getcolor('rgb(124, 124, 124)', mode) ) canvas = ImageDraw.Draw(im) tree = build_tree() draw_tree(tree, canvas) #box = [Point(size/6, size/6) * scale, (Point(size-size/6, size-size/6) * scale)-1] #canvas.rectangle(box, fill=colors[random.randint(0, 1)]) im = im.resize((size*10, size*10)) name = 'level.png' logging.info("Saving to %s" % name) im.save(name)
def ppng(f, names, matrix, nodes, classifier, coloration, signature, outFileName, opt): import Image, ImageColor zoom = 2 steps = classifier(matrix) colors = coloration(0, 1., steps, get_color_html) l = len(nodes) h = l * zoom image = Image.new("RGBA", (h, h)) for i, n in enumerate(nodes): for j in xrange(l): cls, c = get_color(matrix[(i, j)], steps, colors) for k1 in xrange(zoom): for k2 in xrange(zoom): rgba = ImageColor.getcolor(c, "RGBA") image.putpixel((i * zoom + k1, j * zoom + k2), rgba) image.save(f, "png")
def decode(self, code): # decode the code middleType = self.MIDDLE_PATCH_SET[code & 0x03] middleInvert = (code >> 2) & 0x01 cornerType = (code >> 3) & 0x0F cornerInvert = (code >> 7) & 0x01 cornerTurn = (code >> 8) & 0x03 sideType = (code >> 10) & 0x0F sideInvert = (code >> 14) & 0x01 sideTurn = (code >> 15) & 0x03 blue = (code >> 16) & 0x1F green = (code >> 21) & 0x1F red = (code >> 27) & 0x1F foreColor = (red << 3, green << 3, blue << 3) return (middleType, middleInvert, 0), \ (cornerType, cornerInvert, cornerTurn), \ (sideType, sideInvert, sideTurn), \ foreColor, ImageColor.getrgb('white')
def decode(self, code): # decode the code middleType = self.MIDDLE_PATCH_SET[code & 0x03] middleInvert = (code >> 2) & 0x01 cornerType = (code >> 16) & 0x0F cornerInvert = (code >> 7) & 0x01 cornerTurn = (code >> 8) & 0x03 sideType = (code >> 10) & 0x0F sideInvert = (code >> 14) & 0x01 sideTurn = (code >> 15) & 0x03 blue = 127 + (code % 100) # (code << 16) & 0x0F green = 160 #(code >> 21) & 0x1F red = 130 #(code >> 27) & 0x1F #foreColor = (red << 3, green << 3, blue << 3) foreColor = (red, green, blue) return (middleType, middleInvert, 0), \ (cornerType, cornerInvert, cornerTurn), \ (sideType, sideInvert, sideTurn), \ foreColor, ImageColor.getrgb('#FFFFFF')
def __init__(self, eps_xx, eps_zz=None, mu=1.0, color='white', name=None): if eps_zz == None: eps_zz = eps_xx if callable(eps_xx): self.eps_xx = eps_xx else: self.eps_xx = lambda x: eps_xx if callable(eps_zz): self.eps_zz = eps_zz else: self.eps_zz = lambda x: eps_zz if callable(mu): self.mu = mu else: self.mu = lambda x: mu if callable(color): self.color = color else: self.color = lambda x: ImageColor.getrgb(color)
def decode(self, code): # decode the code middleType = self.MIDDLE_PATCH_SET[code & 0x03] middleInvert = (code >> 2) & 0x01 cornerType = (code >> 3) & 0x0F cornerInvert = (code >> 7) & 0x01 cornerTurn = (code >> 8) & 0x03 sideType = (code >> 10) & 0x0F sideInvert = (code >> 14) & 0x01 sideTurn = (code >> 15) & 0x03 blue = (code >> 17) & 0x07 green = (code >> 20) & 0x07 red = (code >> 23) & 0x07 # newly added for iconlang mask = (code >> 26) & 0xFF foreColor = (red << 5, green << 5, blue << 5) return (middleType, middleInvert, 0),\ (cornerType, cornerInvert, cornerTurn),\ (sideType, sideInvert, sideTurn),\ foreColor, ImageColor.getrgb('white'), mask
def warmup(image, midtone, brighten, amount=100): """Apply a toning filter. Move the midtones to the desired color while preserving blacks and whites with optional mixing with original image - amount: 0-100%""" mode = image.mode info = image.info if image.mode != 'L': im = imtools.convert(image, 'L') else: im = image if image.mode != 'RGBA' and imtools.has_transparency(image): image = imtools.convert(image, 'RGBA') luma = imtools.convert(imtools.split(im)[0], 'F') o = [] m = ImageColor.getrgb(midtone) b = brighten / 600.0 # Calculate channels separately for l in range(3): o.append( ImageMath.eval("m*(255-i)*i+i", i=luma, m=4 * ((m[l] / 255.0) - 0.5 + b) / 255.0).convert('L')) colorized = Image.merge('RGB', tuple(o)) if imtools.has_alpha(image): imtools.put_alpha(colorized, imtools.get_alpha(image)) if amount < 100: colorized = imtools.blend(image, colorized, amount / 100.0) return colorized
def brightness(image, amount=50): """Adjust brightness from black to white - amount: -1(black) 0 (unchanged) 1(white) - repeat: how many times it should be repeated""" if amount == 0: return image image = imtools.convert_safe_mode(image) if amount < 0: #fade to black im = imtools.blend(image, Image.new(image.mode, image.size, 0), -amount / 100.0) else: #fade to white im = imtools.blend( image, Image.new(image.mode, image.size, ImageColor.getcolor('white', image.mode)), amount / 100.0) #fix image transparency mask if imtools.has_alpha(image): im.putalpha(imtools.get_alpha(image)) return im
y = 2 * x * y + y0 x = xtemp xSqr = x * x ySqr = y * y i = i + 1 iSpace[pixel_x][pixel_y] = i #Create histogram and total area underneath total = 0 histogram = [0 for i in range(max_iteration + 1)] for x in range(0, width): for y in range(0, height): #print "Dealing with pixel ("+str(x)+","+str(y)+") with i-value "+str(iSpace[x][y]) histogram[iSpace[x][y]] = histogram[iSpace[x][y]] + 1 total = total + 1 #Decide colour for each iteration value hue = [0.0 for i in range(max_iteration + 1)] for i in range(0, max_iteration): hue[i + 1] = hue[i] + (float(histogram[i + 1]) / float(total)) print str(hue[max_iteration]) #Colour in image for x in range(0, width): for y in range(0, height): pixels[x, y] = ImageColor.getrgb("hsl(235,100%," + str(int(hue[iSpace[x][y]] * 100)) + "%)") #Save image img.save("ZoomOutput\output" + str(int(zoomLevel + 1)).zfill(3) + ".bmp") print "Image " + str(int(zoomLevel + 1)) + " complete" #time.sleep(3)
def sepia(white="#fff0c0"): r, g, b = ImageColor.getrgb(white) r = _make_linear_lut(0, r) g = _make_linear_lut(0, g) b = _make_linear_lut(0, b) return ImagePalette("RGB", r + g + b)
startY = centerY - (rangeY / 2) for pixel_x in range(0, width): for pixel_y in range(0, height): x0 = 0.0 y0 = 0.0 x0 = (pixel_x * rangeX) / width + startX y0 = (pixel_y * rangeY) / height + startY if (pixel_y == 0 and pixel_x % 50 == 0): print "Pixels: (" + str(pixel_x) + "," + str( pixel_y) + ") Coords: (" + str(x0) + "," + str(y0) + ")" x = 0.0 y = 0.0 xSqr = 0.0 ySqr = 0.0 i = -1 while (xSqr + ySqr < 4 and i < max_iteration): xtemp = xSqr - ySqr + x0 y = 2 * x * y + y0 x = xtemp xSqr = x * x ySqr = y * y i = i + 1 if i == max_iteration: i = 0 pixels[pixel_x, pixel_y] = ImageColor.getrgb( "hsl(235,100%," + str(int(float(i) / float(max_iteration) * 100)) + "%)") img.save("ZoomOutput\output" + str(int(zoomLevel + 1)).zfill(3) + ".jpg") print "Image " + str(int(zoomLevel + 1)) + " complete" time.sleep(3)
def __init__(self, color, file, size=12): # FIXME: add support for bitmap fonts self.color = ImageColor.getrgb(color) self.font = ImageFont.truetype(file, size)