def binarySearch(minimum, maximum): if minimum == maximum: return minimum mid = (maximum + minimum) / 2 small = (max(mid - 1,minimum) + minimum) / 2 large = (min(mid + 1,maximum) + maximum) / 2 test = abs(image_y / fontImageSize(mid)[1] - aim) test_small = abs(image_y / fontImageSize(small)[0] - aim) test_large = abs(image_y / fontImageSize(large)[0] - aim) best = min(test, test_small, test_large) if best == test_small: return binarySearch(minimum, max(minimum,mid -1)) elif best == test_large: return binarySearch(min(mid+1, maximum), maximum) else: #we might not be at the optimal return binarySearch(small, large)
def genart(self, raw_image): """ Interface function """ image = Image.open(StringIO.StringIO(raw_image)).convert('L') font_size = self.searchFontSize(image) font_image_size = fontImageSize(font_size) symbol_memo = self.fontSymbols(font_size) #we'll ignore the parts that don't fit a full size font for now maxGrid = [x / y for (x, y) in zip(image.size, font_image_size)] if (len([True for x in maxGrid if x == 0]) > 0): return "This image is too small" #temporary way of handling small images #we distribute unused region to all sides startpos = [ (x - y * z) / 2 for (x, y, z) in zip(image.size, font_image_size, maxGrid)] ascii_map = "" #i is height, j is width for i in range(maxGrid[1]): row = "" for j in range(maxGrid[0]): upper_left = (j * font_image_size[0] + startpos[0], i * font_image_size[1] + startpos[1]) b = image.crop((upper_left[0], upper_left[1], upper_left[0] + font_image_size[0], upper_left[1] + font_image_size[1])) row = row + self.KNN(b, symbol_memo) ascii_map = ascii_map + row + '\n' return ascii_map