def create_captcha_background(self, background_avoid): """Create the CAPTCHA background. :param background: color of the background. The color should be a tuple of 3 numbers, such as (0, 255, 255). """ chunk_max = max(1, int(max(self._width, self._height) / 10)) if self._enable_background_noise else 1 chunk = random.randint(1, chunk_max), random.randint(1, chunk_max) image = Image.new('RGB', chunk, (0, 0, 0)) draw = Draw(image) for x in range(chunk[0]): for y in range(chunk[1]): color = random_color(background_avoid, 64) if not self._enable_panda else (0, 0, 0, 255) draw.point((x, y), color) big_side = math.ceil( (self._width * self._width + self._height * self._height)**0.5) + 4 image = image.resize((big_side, big_side), random.choice([Image.NEAREST, Image.BILINEAR])) image = image.rotate(random.random() * 360, random.choice([Image.NEAREST, Image.BILINEAR])) crop_x0 = int((big_side - self._width) / 2) crop_y0 = int((big_side - self._height) / 2) crop_x1 = crop_x0 + self._width crop_y1 = crop_y0 + self._height image = image.crop((crop_x0, crop_y0, crop_x1, crop_y1)) return image
def _draw_map_pices(self, draw: ImageDraw.Draw) -> None: _LOGGER.debug("[_draw_map_pices] Draw") image_x = 0 image_y = 0 for i in range(64): if i > 0: if i % 8 != 0: image_y += 100 else: image_x += 100 image_y = 0 current_piece = self._map_pieces[i] if current_piece.in_use: for x in range(100): current_column = current_piece.points[x] for y in range(100): pixel_type = current_column[y] point_x = image_x + x point_y = image_y + y if (point_x > 6400) or (point_y > 6400): _LOGGER.error( "[get_base64_map] Map Limit 6400!! X: %d Y: %d", point_x, point_y, ) raise RuntimeError("Map Limit reached!") if pixel_type in [0x01, 0x02, 0x03]: draw.point((point_x, point_y), fill=Map.COLORS[pixel_type])
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 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 create_noise_dots(image, number=50): draw = Draw(image) w, h = image.size while number: x1 = random.randint(0, w) y1 = random.randint(0, h) draw.point((x1, y1), fill=random_color(0, 255)) number -= 1 return image
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 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 _filled_by_pixels( image: Image, draw: Draw, pixels: Set[Tuple[int, int]], n: Tuple[int, int], fill: bool, ) -> Generator[Tuple[Image, Draw], None, None]: while len(pixels): for pixel in random.sample(pixels, min(len(pixels), random.randint(*n))): draw.point(pixel, fill=(255 if fill else 0)) pixels.remove(pixel) yield (image, draw)
def getHorizontalImage(self, ml, ap, dv, show=True): """ Return an image of the Horizontal slice at this corrdinate and where in the image does the specified coordinate lie. """ url_data = self.queryServer(ml, ap, dv) self.horizontal_image = fetchImage(url_data['horizontal']['image_url']) coordinates = (url_data['horizontal']['left'], url_data['horizontal']['top']) if show: placement = Draw(self.horizontal_image) placement.point([coordinates]) self.horizontal_image.show() return (self.horizontal_image, coordinates)
def create_image(self): im = Image.new("RGB", self.size, "white") draw = Draw(im) # add horizontal lines to show limits: for v in self.ylines: ry = 1 - (v - self.min_y) / (self.max_y - self.min_y) ry = ry * self.size[1] draw.line(((0, ry), (self.size[0], ry)), "green", 1) # draw values as connected dotes to create a graph last_pos = None for n, v in enumerate(self.store): if v is None: last_pos = None continue ry = 1 - (v - self.min_y) / (self.max_y - self.min_y) pos = (n, ry * self.size[1]) if last_pos is None: draw.point(pos, "black") else: draw.line([last_pos, pos], "black", 1) last_pos = pos self.image = im self.dirty = False
def _create_noise_dots(self, image, color, n_min=80, n_max=120): draw = Draw(image) w, h = image.size n = np.random.randint(n_min, n_max) for _ in range(n): x1 = np.random.randint(0, w) y1 = np.random.randint(0, h) draw.point((x1, y1), fill=color) if np.random.random() < 0.5: draw.point((x1 - 1, y1), fill=color) if np.random.random() < 0.5: draw.point((x1 - 1, y1 - 1), fill=color) if np.random.random() < 0.5: draw.point((x1, y1 - 1), fill=color) 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 put_pixel(x: int, y: int, color: Vector, draw: Draw = draw) -> None: x, y = decode(x, y) if not (x < 0 or x > canvas_width or y < 0 or y > canvas_height): color = int(color[0]), int(color[1]), int(color[2]) draw.point(xy=(x, y), fill=color)
@property def glyph(self): return self._glyph @glyph.setter def glyph(self, value): # Don’t let property be set to a list of None’s pass fnt = BDFWorkaround(open(sys.argv[1], 'rb')) for cps in sys.argv[2:]: cp = int(cps, 16) if cp not in fnt.glyph: continue xy, dst, src, img = fnt.glyph[cp] size = src[2:] d = os.path.join(os.path.dirname(__file__), 'glyphs', 'x'.join( (str(i) for i in size))) f = os.path.join(d, '%08x' % cp) if not os.path.isdir(d): os.mkdir(d) draw = Draw(img) for pos in product(range(img.size[0]), range(img.size[1])): if img.getpixel(pos): draw.point(pos, 0) else: draw.point(pos, 255) img.save(f, 'BMP')