def generateColorSwatch( baseColor, levels, alphaOffset=(.1, .9), lumaOffset=(.1, 1), ): colorsList = [None] * levels for i in range(levels): c = Color(baseColor) baseLum = lumaOffset[1] - c.get_luminance() lumLevel = (baseLum - ((lumaOffset[1]-baseLum)/levels * i)) + (lumaOffset[0]) c.set_luminance(lumLevel) rgb = c.get_rgb() alphaLevel = alphaOffset[0] + ((alphaOffset[1]-alphaOffset[0]) * i/levels) colorsList[i] = (rgb[0], rgb[1], rgb[2], alphaLevel) return colorsList
def upload(): if request.method == 'POST': # Check if there is a file part if 'imagefile' not in request.files: flash('No file part') return render_template('upload.html') image_file = request.files['imagefile'] # Check if there is a selected file if image_file.filename == '': flash('No selected file') return render_template('upload.html') # Check if file type is allowed if not allowed_file(image_file.filename): flash('file type not supported') return render_template('upload.html') if image_file: # Rename extension = image_file.filename.rsplit('.', 1)[1].lower() filename = "{}.{}".format(hash(datetime.now().timestamp()), extension) # Save file path = os.path.join(app.config['UPLOAD_FOLDER'], filename) image_file.save(path) image_file.close() # Process file color = request.form.get('imagebgcolor') color = Color(color) imgpro.centerSquareCrop(path) imgpro.asciiArt(path, path, bg=color.get_rgb()) # Save filename and owner to database conn = sqlite3.connect(DATABASE_NAME) db = conn.cursor() db.execute( "INSERT INTO images(user_rowid, filename) VALUES (?, ?);", (session['user_id'], filename)) conn.commit() conn.close() # Redirect to browse return redirect('/') flash('unknown error') return render_template('upload.html')
def get_color_thumbnail(color: Color) -> Path: """ Retrieve the thumbnail of the given color. The output name will be the corresponding hex strings. If the corresponding file does not exist, it will create it. """ fname = data_path / (str(color.get_hex_l()[1:]) + ".png") if fname.exists(): if fname.is_file(): return fname else: raise FileNotFoundError(f"Thumbnail file exists but it's not a file -> {fname}") # file not there - cache it thumbnail_size = (5, 5) rgb_triad = np.array([c * 255 for c in color.get_rgb()], dtype=np.uint8) mat = np.zeros((*thumbnail_size, 3), dtype=np.uint8) + rgb_triad plt.imsave(fname, mat) return fname
def add_points(self, points, rgbs=None, color=None): """ points must be a Nx3 numpy array, as must rgbs if it is not None """ if not isinstance(points, np.ndarray): points = np.array(points) num_new_points = points.shape[0] self.points = np.append(self.points, points, axis=0) if rgbs is None: color = Color(color) if color else self.color rgbs = np.array([color.get_rgb()] * num_new_points) elif rgbs.shape != points.shape: raise Exception("points and rgbs must have same shape") self.rgbs = np.append(self.rgbs, rgbs, axis=0) if self.has_normals: self.unit_normals = np.append(self.unit_normals, np.apply_along_axis( self.unit_normal, 1, points), axis=0) return self
def add_points(self, points, rgbs = None, color = None): """ points must be a Nx3 numpy array, as must rgbs if it is not None """ if not isinstance(points, np.ndarray): points = np.array(points) num_new_points = points.shape[0] self.points = np.append(self.points, points, axis = 0) if rgbs is None: color = Color(color) if color else self.color rgbs = np.array([color.get_rgb()] * num_new_points) elif rgbs.shape != points.shape: raise Exception("points and rgbs must have same shape") self.rgbs = np.append(self.rgbs, rgbs, axis = 0) if self.has_normals: self.unit_normals = np.append( self.unit_normals, np.apply_along_axis(self.unit_normal, 1, points), axis = 0 ) return self
def add_points(self, points, rgbs=None, color=None): """ points must be a Nx3 numpy array, as must rgbs if it is not None """ points = np.array(points) num_new_points = points.shape[0] self.points = np.append(self.points, points) self.points = self.points.reshape((self.points.size / 3, 3)) if rgbs is None: color = Color(color) if color else self.color rgbs = np.array([color.get_rgb()] * num_new_points) else: if rgbs.shape != points.shape: raise Exception("points and rgbs must have same shape") self.rgbs = np.append(self.rgbs, rgbs) self.rgbs = self.rgbs.reshape((self.rgbs.size / 3, 3)) if self.has_normals: self.unit_normals = np.append( self.unit_normals, np.array([self.unit_normal(point) for point in points])).reshape(self.points.shape) return self
def add_points(self, points, rgbs = None, color = None): """ points must be a Nx3 numpy array, as must rgbs if it is not None """ points = np.array(points) num_new_points = points.shape[0] self.points = np.append(self.points, points) self.points = self.points.reshape((self.points.size / 3, 3)) if rgbs is None: color = Color(color) if color else self.color rgbs = np.array([color.get_rgb()] * num_new_points) else: if rgbs.shape != points.shape: raise Exception("points and rgbs must have same shape") self.rgbs = np.append(self.rgbs, rgbs) self.rgbs = self.rgbs.reshape((self.rgbs.size / 3, 3)) if self.has_normals: self.unit_normals = np.append( self.unit_normals, np.array([self.unit_normal(point) for point in points]) ).reshape(self.points.shape) return self
def asciiArt(image_file, output_file, scale=0, bg=(0, 0, 0)): # Covnert bg to color object bg = Color(rgb=bg) # Open file img = Image.open(image_file) img.load() # Scale if scale == 0: scale = 36 / img.size[0] # Array of chars from dense to sparse chars = numpy.asarray( list( '$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,"^`\'. ' )) # Compute aspect ratio of font width/height font = ImageFont.load_default() font_width, font_height = font.getsize('X') # Resize image to match font aspect ratio letter_width = round(img.size[0] * scale * (font_height / font_width)) letter_height = round(img.size[1] * scale) img = img.resize((letter_width, letter_height)) # Convert image to RGB img.convert('RGBA') temp = img.copy() img = Image.new('RGB', temp.size, tuple(round(i * 255) for i in bg.get_rgb())) alpha = temp.convert('RGBA').split()[-1] img.paste(temp, mask=alpha) # Get a normalized grayscale version img_grayscale = img.convert(mode='L') img_grayscale = ImageOps.autocontrast(img_grayscale) # Invert if bg is near black if bg.get_luminance() < 0.5: img_grayscale = ImageOps.invert(img_grayscale) # Remap values to 0 to chars.size - 1 img_grayscale = ImageMath.eval("a * factor / 255", { 'a': img_grayscale, 'factor': chars.size - 1 }) # Generate ascii art rows = chunks(list(img_grayscale.getdata()), img_grayscale.size[0]) rows = [''.join(chars[row]) for row in rows] # Create blank image and drawer newimg = Image.new( "RGB", (letter_width * font_width, letter_height * font_height), tuple(round(i * 255) for i in bg.get_rgb())) drawer = ImageDraw.Draw(newimg) color_generator = (i for i in img.getdata()) y = 0 for row in rows: x = 0 for c in row: color = tuple(next(color_generator)) drawer.text((x, y), c, color, font=font) x += font_width # print(c, end='') y += font_height # print() # print("Showing newimg") # newimg.show() newimg.save(output_file) return rows
def zone_wise_distribution(): data = get_full_trains() station_data = get_station_data() # Except sububan and passenger trains division = ["0", "1", "2", "6", "7"] zone_counter = Counter() subdata = defaultdict(list) for r in data: try: if len(r.train_number) == 5: if r.origin_code in station_data.keys(): zone = station_data[r.origin_code][-1] if len(zone.strip()) > 0: zone_counter.update({zone}) subdata[zone].append(r) except (TypeError, ValueError) as e: pass names = [] values = [] ld = "Long Distance" su = "Suburban" for v in subdata: temp = defaultdict(int) for r in subdata[v]: letter = str(r.train_number)[0] if letter in division: temp[ld] = temp[ld] + 1 else: temp[su] = temp[su] + 1 temp_list = [temp[ld], temp[su]] names.append(v) values.append(temp_list) fig, ax = plt.subplots() size = 0.3 vals = np.array(values) ot = np.linspace(0.1, 0.9, len(vals)) cmap = plt.get_cmap("tab20b") outer_colors = [cmap(x) for x in ot] inner = [] decrease = 0.25 # Percent dark # Change color of inner pie for k in outer_colors: r, g, b, a = k col2 = Color(rgb=(r - (r * decrease), g - (g * decrease), b - (b * decrease))) inner = inner + [col2.get_rgb(), (r, g, b, 0.6)] inner_colors = [x for x in inner] ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors, wedgeprops=dict(width=size, edgecolor='w'), startangle=90) ax.pie(vals.flatten(), radius=1 - size, colors=inner_colors, wedgeprops=dict(width=size, edgecolor='w'), startangle=90) print(sum(vals.flatten())) ax.set(aspect="equal") plt.show()
def color_to_rgb(color): if not isinstance(color, Color): color = Color(color) return np.array(color.get_rgb())