def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2): ranges = { "shearX": np.linspace(0, 0.3, 10), "shearY": np.linspace(0, 0.3, 10), "translateX": np.linspace(0, 150 / 331, 10), "translateY": np.linspace(0, 150 / 331, 10), "rotate": np.linspace(0, 30, 10), "color": np.linspace(0.0, 0.9, 10), "posterize": np.round(np.linspace(8, 4, 10), 0).astype(np.int), "solarize": np.linspace(256, 0, 10), "contrast": np.linspace(0.0, 0.9, 10), "sharpness": np.linspace(0.0, 0.9, 10), "brightness": np.linspace(0.0, 0.9, 10), "autocontrast": [0] * 10, "equalize": [0] * 10, "invert": [0] * 10 } func = { "shearX": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, magnitude * random.choice( [-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fillcolor=(128, 128, 128)), "shearY": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, 0, 0, magnitude * random. choice([-1, 1]), 1, 0), Image.BICUBIC, fillcolor=(128, 128, 128)), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * random.choice( [-1, 1]), 0, 1, 0), fillcolor=(128, 128, 128)), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * random. choice([-1, 1])), fillcolor=(128, 128, 128)), "rotate": lambda img, magnitude: img.rotate(magnitude * random.choice( [-1, 1])), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( 1 + magnitude * random.choice([-1, 1])), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * random.choice([-1, 1])), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img) } # self.name = "{}_{:.2f}_and_{}_{:.2f}".format( # operation1, ranges[operation1][magnitude_idx1], # operation2, ranges[operation2][magnitude_idx2]) self.p1 = p1 self.operation1 = func[operation1] self.magnitude1 = ranges[operation1][magnitude_idx1] self.p2 = p2 self.operation2 = func[operation2] self.magnitude2 = ranges[operation2][magnitude_idx2]
def generate(tiles, mask, offset): """ Generate a giant tiled image to certain specs """ # each image will be 48px square - why that size? because some images were # saved out at that resolution (anything ending *normal without extension) # giving a total image size of a fairly manageable 15,216px square pixels = read_mask(mask) tiles = iglob(tiles) # We use 317 as 317^2 = 100489 which is the smallest square integer # that fits 100,000 'pixels'. A pixel in this case will be a twitter profile # Each tile is 48x48 (hardcodes - could get from first tile when looped) per_side = 317 tile_size = (48, 48) sql_script = open('map/coords.sql', 'w') con = mdb.connect('localhost', 'root', os.environ['DBPASS'], 'def100k'); cur = con.cursor() try: os.mkdir('tiles') except OSError: pass def _get_tile(): """ Repeatedly try and return a valid PIL image """ tile = tiles.next() try: i = Image.open(tile) # If the image is indexed then when PIL converts to RGB (for brightness) # a bug means it'll return an all white image. This is recent (like 09/13) # http://stackoverflow.com/questions/19892919/pil-converting-an-image-with-mode-i-to-rgb-results-in-a-fully-white-image # So lets log that for now and move on with a new image mode = i.mode if mode != 'I': return i, tile else: print "[Skipping] IndexedMode: %s" % tile return _get_tile() except IOError: print "[Skipping] IOError: %s" % tile return _get_tile() for row_num, row in enumerate(pixels): row_image = Image.new('RGB', (tile_size[0] * per_side, tile_size[1])) for num, pixel in enumerate(row): ypos = row_num + offset tile_score = score(pixel) src_tile, src_name = _get_tile() if tile_score > 128: # For 'white' tiles use a bright version try: image = ImageEnhance.Brightness(src_tile).enhance(1.33) except ValueError: # Might get a conversion error, skip for now and use as is image = src_tile else: # For dark tiles use a darkened version try: image = ImageEnhance.Brightness(src_tile).enhance(0.37) except ValueError: image = src_tile # If we have dark tiles use black and white version # image = src_tile.convert('L') # TODO: HACK!! filename = src_name.replace('avatars/batch1/', '') filename = src_name.replace('avatars/batch2/', '') # note we are only shifting across! each row is output individually # rather than one giant image row_image.paste(image, (num * tile_size[0], 0)) # Store the tile location for this so we can look it up and add a marker # easily on the finished map. Note there's stmt = """ UPDATE images SET xpos=%d, ypos=%d WHERE filename="%s"; """ % (num, ypos, filename) sql_script.write(stmt) cur.execute(stmt) con.commit() print stmt image_name = 'tiles/row_%03d.png' % ypos row_image.save(image_name) print "Output %s" % image_name sql_script.close() con.close()
def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128)): ranges = { "shearX": np.linspace(0, 0.3, 10), "shearY": np.linspace(0, 0.3, 10), "translateX": np.linspace(0, 150 / 331, 10), "translateY": np.linspace(0, 150 / 331, 10), "rotate": np.linspace(0, 30, 10), "color": np.linspace(0.0, 0.9, 10), "posterize": np.round(np.linspace(8, 4, 10), 0).astype(np.int), "solarize": np.linspace(256, 0, 10), "contrast": np.linspace(0.0, 0.9, 10), "sharpness": np.linspace(0.0, 0.9, 10), "brightness": np.linspace(0.0, 0.9, 10), "autocontrast": [0] * 10, "equalize": [0] * 10, "invert": [0] * 10 } # from https://stackoverflow.com/questions/5252170/specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand def rotate_with_fill(img, magnitude): rot = img.convert("RGBA").rotate(magnitude) return Image.composite(rot, Image.new("RGBA", rot.size, (128, ) * 4), rot).convert(img.mode) func = { "shearX": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, magnitude * random.choice( [-1, 1]), 0, 0, 1, 0), Image.BICUBIC, fillcolor=fillcolor), "shearY": lambda img, magnitude: img.transform(img.size, Image.AFFINE, (1, 0, 0, magnitude * random. choice([-1, 1]), 1, 0), Image.BICUBIC, fillcolor=fillcolor), "translateX": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * random.choice( [-1, 1]), 0, 1, 0), fillcolor=fillcolor), "translateY": lambda img, magnitude: img.transform( img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * random. choice([-1, 1])), fillcolor=fillcolor), "rotate": lambda img, magnitude: rotate_with_fill(img, magnitude), "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( 1 + magnitude * random.choice([-1, 1])), "posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude), "solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude), "contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance( 1 + magnitude * random.choice([-1, 1])), "sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance( 1 + magnitude * random.choice([-1, 1])), "autocontrast": lambda img, magnitude: ImageOps.autocontrast(img), "equalize": lambda img, magnitude: ImageOps.equalize(img), "invert": lambda img, magnitude: ImageOps.invert(img) } self.p1 = p1 self.operation1 = func[operation1] self.magnitude1 = ranges[operation1][magnitude_idx1] self.p2 = p2 self.operation2 = func[operation2] self.magnitude2 = ranges[operation2][magnitude_idx2]
def Brightness(image): return numpy.array( ImageEnhance.Brightness(Image.fromarray(image)).enhance(0.5))
def enhance(image): enhancer = ImageEnhance.Contrast(image) image = enhancer.enhance(5) enhancer = ImageEnhance.Brightness(image) image = enhancer.enhance(10.0) return image
def load_image_and_process(im, im_dst, flag, output_shape=(512, 512), prefix_path='train_raw/', transfo_params=None, rand_values=None): # target = prefix_path + im + '.jpeg' target = prefix_path + im im_default = np.zeros((width, height, 3), dtype='float32') if not os.path.exists(target): im_dst[:] = im_default flag = 1 return flag = 0 im = Image.open(target, mode='r') im_new = im # im_new.show() chosen_values = {} if transfo_params.get('extra_width_crop', False): w, h = im_new.size if w / float(h) >= 1.3: cols_thres = np.where( np.max(np.max(np.asarray(im_new), axis=2), axis=0) > 35)[0] # Extra cond compared to orig crop. if len(cols_thres) > output_shape[0] // 2: min_x, max_x = cols_thres[0], cols_thres[-1] else: min_x, max_x = 0, -1 im_new = im_new.crop((min_x, 0, max_x, h)) if transfo_params.get('crop_height', False): w, h = im_new.size if w > 1 and 0.98 <= h / float(w) <= 1.02: # "Normal" without height crop, do height crop. im_new = im_new.crop((0, int(0.05 * h), w, int(0.95 * h))) if transfo_params.get('crop', False) and not \ transfo_params.get('crop_after_rotation', False): if rand_values: do_crop = rand_values['do_crop'] else: do_crop = transfo_params['crop_prob'] > np.random.rand() chosen_values['do_crop'] = do_crop if do_crop: out_w, out_h = im_new.size w_dev = int(transfo_params['crop_w'] * out_w) h_dev = int(transfo_params['crop_h'] * out_h) # If values are supplied. if rand_values: w0, w1 = rand_values['w0'], rand_values['w1'] h0, h1 = rand_values['h0'], rand_values['h1'] else: w0 = np.random.randint(0, w_dev + 1) w1 = np.random.randint(0, w_dev + 1) h0 = np.random.randint(0, h_dev + 1) h1 = np.random.randint(0, h_dev + 1) # Add params to dict. chosen_values['w0'] = w0 chosen_values['w1'] = w1 chosen_values['h0'] = h0 chosen_values['h1'] = h1 im_new = im_new.crop((0 + w0, 0 + h0, out_w - w1, out_h - h1)) if transfo_params.get('shear', False): if transfo_params['shear_prob'] > np.random.rand(): # print 'shear' # TODO: No chosen values because shear not really used. shear_min, shear_max = transfo_params['shear_range'] m = shear_min + np.random.rand() * (shear_max - shear_min) out_w, out_h = im_new.size xshift = abs(m) * out_w new_width = out_w + int(round(xshift)) im_new = im_new.transform((new_width, out_h), Image.AFFINE, (1, m, -xshift if m > 0 else 0, 0, 1, 0), Image.BICUBIC) if transfo_params.get('rotation_before_resize', False): if rand_values: rotation_param = rand_values['rotation_param'] else: rotation_param = np.random.randint( transfo_params['rotation_range'][0], transfo_params['rotation_range'][1]) chosen_values['rotation_param'] = rotation_param im_new = im_new.rotate(rotation_param, resample=Image.BILINEAR, expand=transfo_params.get( 'rotation_expand', False)) if transfo_params.get('rotation_expand', False): im_new = im_new.crop(im_new.getbbox()) if transfo_params.get('crop_after_rotation', False): if rand_values: do_crop = rand_values['do_crop'] else: do_crop = transfo_params['crop_prob'] > np.random.rand() chosen_values['do_crop'] = do_crop if do_crop: out_w, out_h = im_new.size w_dev = int(transfo_params['crop_w'] * out_w) h_dev = int(transfo_params['crop_h'] * out_h) # If values are supplied. if rand_values: w0, w1 = rand_values['w0'], rand_values['w1'] h0, h1 = rand_values['h0'], rand_values['h1'] else: w0 = np.random.randint(0, w_dev + 1) w1 = np.random.randint(0, w_dev + 1) h0 = np.random.randint(0, h_dev + 1) h1 = np.random.randint(0, h_dev + 1) # Add params to dict. chosen_values['w0'] = w0 chosen_values['w1'] = w1 chosen_values['h0'] = h0 chosen_values['h1'] = h1 im_new = im_new.crop((0 + w0, 0 + h0, out_w - w1, out_h - h1)) if transfo_params.get('keep_aspect_ratio', False): im_new = make_thumb(im_new, size=output_shape, pad=transfo_params['resize_pad']) else: im_new = im_new.resize(output_shape, resample=Image.BILINEAR) if transfo_params.get('rotation', False) \ and not transfo_params.get('rotation_before_resize', False): if rand_values: rotation_param = rand_values['rotation_param'] else: rotation_param = np.random.randint( transfo_params['rotation_range'][0], transfo_params['rotation_range'][1]) chosen_values['rotation_param'] = rotation_param im_new = im_new.rotate(rotation_param, resample=Image.BILINEAR, expand=transfo_params.get( 'rotation_expand', False)) if transfo_params.get('rotation_expand', False): im_new = im_new.crop(im_new.getbbox()) if transfo_params.get('contrast', False): contrast_min, contrast_max = transfo_params['contrast_range'] if rand_values: contrast_param = rand_values['contrast_param'] else: contrast_param = np.random.uniform(contrast_min, contrast_max) chosen_values['contrast_param'] = contrast_param im_new = ImageEnhance.Contrast(im_new).enhance(contrast_param) if transfo_params.get('brightness', False): brightness_min, brightness_max = transfo_params['brightness_range'] if rand_values: brightness_param = rand_values['brightness_param'] else: brightness_param = np.random.uniform(brightness_min, brightness_max) chosen_values['brightness_param'] = brightness_param im_new = ImageEnhance.Brightness(im_new).enhance(brightness_param) if transfo_params.get('color', False): color_min, color_max = transfo_params['color_range'] if rand_values: color_param = rand_values['color_param'] else: color_param = np.random.uniform(color_min, color_max) chosen_values['color_param'] = color_param im_new = ImageEnhance.Color(im_new).enhance(color_param) if transfo_params.get('flip', False): if rand_values: do_flip = rand_values['do_flip'] else: do_flip = transfo_params['flip_prob'] > np.random.rand() chosen_values['do_flip'] = do_flip if do_flip: im_new = im_new.transpose(Image.FLIP_LEFT_RIGHT) if output_shape[0] < 200 and False: # Otherwise too slow. # TODO: Disabled for now if 'rotation' in transfo_params and transfo_params['rotation']: if rand_values: rotation_param = rand_values['rotation_param2'] else: rotation_param = np.random.randint( transfo_params['rotation_range'][0], transfo_params['rotation_range'][1]) im_new = im_new.rotate(rotation_param, resample=Image.BILINEAR, expand=False) chosen_values['rotation_param2'] = rotation_param if transfo_params.get('zoom', False): if rand_values: do_zoom = rand_values['do_zoom'] else: do_zoom = transfo_params['zoom_prob'] > np.random.rand() chosen_values['do_zoom'] = do_zoom if do_zoom: zoom_min, zoom_max = transfo_params['zoom_range'] out_w, out_h = im_new.size if rand_values: w_dev = rand_values['w_dev'] else: w_dev = int(np.random.uniform(zoom_min, zoom_max) / 2 * out_w) chosen_values['w_dev'] = w_dev im_new = im_new.crop( (0 + w_dev, 0 + w_dev, out_w - w_dev, out_h - w_dev)) if im_new.size != output_shape: im_new = im_new.resize(output_shape, resample=Image.BILINEAR) im_new.show() im_new = np.asarray(im_new).astype('float32') / 255 im_dst[:] = im_new im.close() del im, im_new return chosen_values
def brightnessEnhancement(root_path, img_name): # 亮度增强 image = Image.open(os.path.join(root_path, img_name)) enh_bri = ImageEnhance.Brightness(image) brightness = 1.5 image_brightened = enh_bri.enhance(brightness)
def ELA(imgfile,type): ## TYPE 1 (IMAGE) --- TYPE 2 (URL) ## # Load Original Image # original = None if type == 1: original = Image.open(imgfile) elif type == 2: # Download the file # urllib.request.urlretrieve(imgfile, filename) original = Image.open(filename) if original is None: return 'Couldnt process your request.' # Convert to Black and White # original = original.convert('L') original = ImageEnhance.Sharpness(original).enhance(0.0) print('Image: %s' %(filename)) # Compress at 70% # original.save(TEMP,'JPEG',quality=quality) temporary = Image.open(TEMP) # Find Difference between original and temporary # diff = ImageChops.difference(original, temporary) # Find the max value of color band in image # extrema = diff.getextrema() max_diff = extrema[1] print('Extrema: %d' %(max_diff),end=' ') scale = 255.0/max_diff # Enhance the image based on that scale # diff = ImageEnhance.Brightness(diff).enhance(scale) # Fetch the histogram of the difference image (Count of color pixels) # lists = diff.histogram(mask=None, extrema=None) # Calculate Threshold by keeping last 75 pixels # pixels = 0 for i in range(255,1,-1): if pixels+lists[i] <= 75: pixels += lists[i] else: threshold = i+1 print('Threshold: %d' %(threshold),end=' ') break # Apply Threshold # bw = diff.point(lambda x: 0 if x < threshold else 255, '1') # Calculate Radius # WIDTH, HEIGHT = bw.size RADIUS = int(math.sqrt((WIDTH*HEIGHT)/(3.14*625.23))) print('Radius: %d' %(RADIUS)) # Maintain a pixel array (Pixel Number : X-Y Co-ordinate) # coordinates = [] # EDGES {(V1->V2) (V2->V3) (V4->V5)}# edges = [] # Scan the entire image and fetch co-ordinates of white pixels # bwa = bw.load() for x in range(WIDTH): for y in range(HEIGHT): # Fetch each pixel # # color = bw.getpixel((x,y)) color = bwa[x,y] # If pixel is white, record its co-ordinates # if color==255: coordinates.append([x,y]) # Loop through XY Co-Ordinates and find Edges # for coord in coordinates: index = coordinates.index(coord) x1 = coord[0] y1 = coord[1] for next_index in range(index+1,len(coordinates)): x2 = coordinates[next_index][0] y2 = coordinates[next_index][1] distance = math.sqrt(((x1-x2)**2)+((y1-y2)**2)) if (distance < (2*RADIUS)): edges.append([index,next_index]) # Create a list that has connections for every pixel (V1:V2,V3,...) (V2:V1,V2,...) # connectedPixelsList = [] # No of white pixels # total_white_pixels = len(coordinates) connectedPixelsList = getConnectedPixels(edges,total_white_pixels) # Labels of clusters (Starting value -> 100) # labelCount = 100 # Dictionary (Pixel:Label) # label_of_pixels = {} # Assign every pixel a label of 0 # for index in range(0,len(connectedPixelsList)): label_of_pixels.update({connectedPixelsList[index][0]:0}) # Check neighbor of every pixel and find the root label of every pixel # for index in range(0,len(connectedPixelsList)): element = connectedPixelsList[index] # Arbitrary root number # root = 1000 # Find label with lowest value and assign to root # for i in range(1,len(element)): pixel = element[i] label = label_of_pixels.get(pixel) if label > 0 and root > label: root = label # Union-Find Algorithm # # If no root found, assign an arbitrary label # if root == 1000: labelCount += 1 label_of_pixels.update({element[0]:labelCount}) else: # Update all pixels with root as label # for i in range(0,len(element)): pixel = element[i] label_of_pixels.update({pixel:root}) # # Count the number of white pixels for each label # color_count = {} for lp in label_of_pixels.items(): label = lp[1] if label not in color_count: color_count.update({label:1}) else: color_count.update({label:color_count.get(label)+1}) # White Pixels in each Cluster # print('White pixels in each cluster: ',end=' ') max = 0 for p in color_count.values(): if max < p: max = p print(p,end=' ') print() print('Max: %d' %(max)) maxToTotalRatio = (max/total_white_pixels)*100 if maxToTotalRatio > 80: return {'maxToTotalRatio':maxToTotalRatio,'edited':True} else: return {'maxToTotalRatio':maxToTotalRatio,'edited':False}
def data_generator(batch_size, w, h, rotate=False, crop=True, enhance_range=0.3): #return data Y = np.zeros((batch_size * 2, 389)) X = np.zeros((batch_size * 2, w, h, 3)) feature = np.zeros((388, )) counter = 0 while True: #generate batch for i in range(batch_size): # randomly read correct/incorrect samples pos_img = PIL.Image.open(data_dir + '\\img_pos\\' + y_index[str(counter)]).convert('RGB') neg_img = PIL.Image.open(data_dir + '\\img_neg\\' + y_neg_list[counter]).convert('RGB') feature[:] = y_data[counter] #crop if crop == True: width, height = pos_img.size max_x, min_x, max_y, min_y = get_bounding_box(feature) if min_x >= 0 and min_y >= 0 and max_x <= 1 and max_y <= 1: left = np.random.uniform(0, min_x) right = np.random.uniform(max_x, 1) top = np.random.uniform(0, min_y) bottom = np.random.uniform(max_y, 1) feature = feature.reshape(-1, 2) feature[:, 0] = (feature[:, 0] - left) * (1 / (right - left)) feature[:, 1] = (feature[:, 1] - top) * (1 / (bottom - top)) feature = np.squeeze(feature.reshape(1, -1), 0) pos_img = pos_img.crop((left * width, top * height, right * width, bottom * height)) width, height = neg_img.size neg_img = neg_img.crop( (np.random.uniform(0, 0.25) * width, np.random.uniform(0, 0.25) * height, np.random.uniform(0.75, 1) * width, np.random.uniform(0.75, 1) * height)) #resize pos_img = pos_img.resize((w, h)) neg_img = neg_img.resize((w, h)) #rotate if rotate == True: angle = (np.random.randint(0, 3) * 90) - 90 feature = rotate_axis(feature, angle) pos_img = pos_img.rotate(angle) angle = (np.random.randint(0, 3) * 90) - 90 neg_img = neg_img.rotate(angle) #random brightness, contrast and color pos_img = ImageEnhance.Brightness(pos_img).enhance( 1 + np.random.uniform(0, enhance_range) - (enhance_range / 2)) pos_img = ImageEnhance.Color(pos_img).enhance( 1 + np.random.uniform(0, enhance_range) - (enhance_range / 2)) pos_img = ImageEnhance.Contrast(pos_img).enhance( 1 + np.random.uniform(0, enhance_range) - (enhance_range / 2)) neg_img = ImageEnhance.Brightness(neg_img).enhance( 1 + np.random.uniform(0, enhance_range) - (enhance_range / 2)) neg_img = ImageEnhance.Color(neg_img).enhance( 1 + np.random.uniform(0, enhance_range) - (enhance_range / 2)) neg_img = ImageEnhance.Contrast(neg_img).enhance( 1 + np.random.uniform(0, enhance_range) - (enhance_range / 2)) #generate train data X[i] = np.array(pos_img) / 255 X[batch_size + i] = np.array(neg_img) / 255 #it's not a background therefore 0 position is 1 Y[i, 0] = 1 Y[i, 1:] = feature counter += 1 counter %= len(y_index) #shuffle data index = np.arange(0, batch_size * 2) np.random.shuffle(index) yield (X[index], Y[index])
def bright_img(img, br=2): enh = ImageEnhance.Brightness(img) return enh.enhance(br)
def tweak_image_brightness(image): # Tweak the image's brightness - got the idea from https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9#.ndechdida enhancer = ImageEnhance.Brightness(image) return enhancer.enhance(random.uniform(0.2, 1.8))
def data_Brightness(self, image_input, ength_Value): # 亮度增强 enh = ImageEnhance.Brightness(image_input) result = enh.enhance(ength_Value) return result
def transform_image(self, image, magnitude=0, direction=1): value = 1 + self.magnitude_range[magnitude] * direction return ImageEnhance.Brightness(image).enhance(value)
def process_image(self): if self.step_x is None: step = UNITS_PER_INCH / self.dpi self.step_x = step self.step_y = step from PIL import Image, ImageEnhance, ImageFilter, ImageOps from meerk40t.image.actualize import actualize from meerk40t.image.imagetools import dither image = self.image main_matrix = self.matrix r = self.red * 0.299 g = self.green * 0.587 b = self.blue * 0.114 v = self.lightness c = r + g + b try: c /= v r = r / c g = g / c b = b / c except ZeroDivisionError: pass if image.mode != "L": image = image.convert("RGB") image = image.convert("L", matrix=[r, g, b, 1.0]) if self.invert: image = image.point(lambda e: 255 - e) # Calculate device real step. step_x, step_y = self.step_x, self.step_y if ( main_matrix.a != step_x or main_matrix.b != 0.0 or main_matrix.c != 0.0 or main_matrix.d != step_y ): try: image, actualized_matrix = actualize( image, main_matrix, step_x=step_x, step_y=step_y, inverted=self.invert, ) except (MemoryError, DecompressionBombError): self.process_image_failed = True return else: actualized_matrix = Matrix(main_matrix) if self.invert: empty_mask = image.convert("L").point(lambda e: 0 if e == 0 else 255) else: empty_mask = image.convert("L").point(lambda e: 0 if e == 255 else 255) # Process operations. for op in self.operations: name = op["name"] if name == "crop": try: if op["enable"] and op["bounds"] is not None: crop = op["bounds"] left = int(crop[0]) upper = int(crop[1]) right = int(crop[2]) lower = int(crop[3]) image = image.crop((left, upper, right, lower)) except KeyError: pass elif name == "edge_enhance": try: if op["enable"]: if image.mode == "P": image = image.convert("L") image = image.filter(filter=ImageFilter.EDGE_ENHANCE) except KeyError: pass elif name == "auto_contrast": try: if op["enable"]: if image.mode not in ("RGB", "L"): # Auto-contrast raises NotImplementedError if P # Auto-contrast raises OSError if not RGB, L. image = image.convert("L") image = ImageOps.autocontrast(image, cutoff=op["cutoff"]) except KeyError: pass elif name == "tone": try: if op["enable"] and op["values"] is not None: if image.mode == "L": image = image.convert("P") tone_values = op["values"] if op["type"] == "spline": spline = ImageNode.spline(tone_values) else: tone_values = [q for q in tone_values if q is not None] spline = ImageNode.line(tone_values) if len(spline) < 256: spline.extend([255] * (256 - len(spline))) if len(spline) > 256: spline = spline[:256] image = image.point(spline) if image.mode != "L": image = image.convert("L") except KeyError: pass elif name == "contrast": try: if op["enable"]: if op["contrast"] is not None and op["brightness"] is not None: contrast = ImageEnhance.Contrast(image) c = (op["contrast"] + 128.0) / 128.0 image = contrast.enhance(c) brightness = ImageEnhance.Brightness(image) b = (op["brightness"] + 128.0) / 128.0 image = brightness.enhance(b) except KeyError: pass elif name == "gamma": try: if op["enable"] and op["factor"] is not None: if image.mode == "L": gamma_factor = float(op["factor"]) def crimp(px): px = int(round(px)) if px < 0: return 0 if px > 255: return 255 return px if gamma_factor == 0: gamma_lut = [0] * 256 else: gamma_lut = [ crimp(pow(i / 255, (1.0 / gamma_factor)) * 255) for i in range(256) ] image = image.point(gamma_lut) if image.mode != "L": image = image.convert("L") except KeyError: pass elif name == "unsharp_mask": try: if ( op["enable"] and op["percent"] is not None and op["radius"] is not None and op["threshold"] is not None ): unsharp = ImageFilter.UnsharpMask( radius=op["radius"], percent=op["percent"], threshold=op["threshold"], ) image = image.filter(unsharp) except (KeyError, ValueError): # Value error if wrong type of image. pass elif name == "halftone": try: if op["enable"]: image = RasterScripts.halftone( image, sample=op["sample"], angle=op["angle"], oversample=op["oversample"], black=op["black"], ) except KeyError: pass if empty_mask is not None: background = Image.new(image.mode, image.size, "white") background.paste(image, mask=empty_mask) image = background # Mask exists use it to remove any pixels that were pure reject. if self.dither and self.dither_type is not None: if self.dither_type != "Floyd-Steinberg": image = dither(image, self.dither_type) image = image.convert("1") inverted_main_matrix = Matrix(main_matrix).inverse() self.processed_matrix = actualized_matrix * inverted_main_matrix self.processed_image = image # self.matrix = actualized_matrix self.altered() self.process_image_failed = False
def random_brightness(img, lower=0.6, upper=1.4): factor = random.uniform(lower, upper) img = ImageEnhance.Brightness(img) img = img.enhance(factor) return img
def enhancer(): # import files from folder for image in dirs: if os.path.isfile(path + image): source = Image.open(path + image) f, e = os.path.splitext(path + image) # # Two image source inputs filter separately with DETAIL and # FIND_EDGES filters. # # http://pillow.readthedocs.io/en/3.4.x/reference/ImageFilter.html # filter1 = source.filter(ImageFilter.DETAIL) filter2 = source.filter(ImageFilter.FIND_EDGES) # # One image with DETAIL filtered and the second image with FIND_EDGES # filtered. Two filtered image blends together with alpha 0.1 overlays. # http://pillow.readthedocs.io/en/3.4.x/reference/Image.html?highlight=blend#PIL.Image.blend # compose = Image.blend(filter1, filter2, alpha=.1) # # Taking from the first image blend (compose) and blend it again with the # SMOOTH filter as a new image source input. Alpha is 0.1 overlays. # filter3 = source.filter(ImageFilter.SMOOTH) blend = Image.blend(compose, filter3, alpha=.1) # # The final blending (blend) is move to enhancing stage. # This stage is to enhance the image COLOR with value 1.5 (0.0). # IMAGE > enhanced > COLOR # # http://pillow.readthedocs.io/en/3.4.x/reference/ImageEnhance.html?highlight=ImageEnhance#PIL.ImageEnhance.Color # imageColor = ImageEnhance.Color(blend) renderStage1 = imageColor.enhance(1.5) # # This stage is to enhance the image CONTRAST with value 1.1 (0.0). # IMAGE(color) > enhanced > CONTRAST # # http://pillow.readthedocs.io/en/3.4.x/reference/ImageEnhance.html?highlight=ImageEnhance#PIL.ImageEnhance.Contrast # imageContrast = ImageEnhance.Contrast(renderStage1) renderStage2 = imageContrast.enhance(1.1) # # This stage is to enhance the image CONTRAST with value 1.1 (0.0). # IMAGE(contrast) > enhanced > BRIGHTNESS # # http://pillow.readthedocs.io/en/3.4.x/reference/ImageEnhance.html?highlight=ImageEnhance#PIL.ImageEnhance.Brightness # imageBrightness = ImageEnhance.Brightness(renderStage2) renderFinal = imageBrightness.enhance(1.1) # # Final, write to a new image file # File Format is JPEG with Quality 100 renderFinal.save(f + '_enhanced.jpg', 'JPEG', quality=100)
elif option == 'mr': print("Please wait...") image = Image.open(image_name) mirrored = ImageOps.mirror(image) mirrored.save('{}{}'.format('mirrored', image_name)) print('Successful!\n') mirrored.show() elif option == 'bn': print("Please wait...") b = input( 'Enter the brightness value you\'d like to add (1 is stock I am float friendly)' ) image = Image.open(image_name) brightened = ImageEnhance.Brightness(image).enhance(float(b)) brightened.save('{}{}'.format('brightened', image_name)) print('Successful!\n') brightened.show() elif option == 'bw': print("Please wait...") image = Image.open(image_name) bw = image.convert('L') bw.save('{}{}'.format('bw', image_name)) print('Successful!\n') bw.show() elif option == 'flt': image = Image.open(image_name) choice = input(
def main(): np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning) args = parse_args() image_paths = get_image_paths(args['image'], args['directory']) plate_size = args['plate_size'] global small_plaques global debug_mode small_plaques = args['small_plaque'] debug_mode = args['debug'] for image_path in image_paths: print("Processing " + image_path) # adjust too bright image #average image brightness image_brightness = get_brightness(image_path) im = Image.open(image_path) image = cv2.imread(image_path) if image_brightness > 70: #im = Image.open(image_tmp) enhancer = ImageEnhance.Brightness(im) factor = 0.5 im_output = enhancer.enhance(factor) im_output.save(image_path + '.tmp' + os.path.splitext(image_path)[1]) image = cv2.imread(image_path + '.tmp' + os.path.splitext(image_path)[1]) binary_image, high_contrast, clr_high_contrast = process_image( image, 2.5) # cv2.imshow("Binary image", binary_image) contours = get_contours(binary_image) image_size = binary_image.shape green_df, red_df, other_df, plate_df = filter_contours( contours, image_size) # Filter plaques duplicates (circle in circle) in valid plaques and plates green_df_copy = green_df.copy() plate_df_copy = plate_df.copy() green_df_copy = check_duplicate_plaques(green_df_copy) plate_df_copy = check_duplicate_plaques(plate_df_copy) red_df_copy = red_df.copy() other_df_copy = other_df.copy() green_df_copy = calculate_size_mm(plate_size, green_df_copy, plate_df) red_df_copy = calculate_size_mm(plate_size, red_df_copy, plate_df) other_df_copy = calculate_size_mm(plate_size, other_df_copy, plate_df) plate_df_copy = calculate_size_mm(plate_size, plate_df_copy, plate_df) if (green_df_copy.size > 0): # get Petri dish size and adjust plaques sizes green_df_copy['MEAN_COLOUR'] = green_df_copy.apply( lambda x: get_mean_grey_colour(high_contrast, x['CONTOURS']), axis=1) green_df_copy['MEAN_COLOUR'] = green_df_copy.apply( lambda x: get_mean_grey_colour(clr_high_contrast, x['CONTOURS'] ), axis=1) #Remove extra black contours #TODO dark plaques are being filtered out (online_image.png filter_dev_colour = green_df_copy.apply( lambda x: abs(x['MEAN_COLOUR']) < 40, axis=1) green_df_copy = green_df_copy[~filter_dev_colour] else: green_df_copy['MEAN_COLOUR'] = 0 green_df_copy = renumerate_df(green_df_copy) renumerate_df(red_df) renumerate_df(other_df) output = draw_contours(clr_high_contrast, green_df_copy, red_df_copy, other_df_copy, plate_df_copy) if not os.path.exists(out_dir_path): os.makedirs(out_dir_path) write_images(out_dir_path, output, binary_image, high_contrast, image_path) #Delete the temporary file if os.path.exists(image_path + '.tmp' + os.path.splitext(image_path)[1]): os.remove(image_path + '.tmp' + os.path.splitext(image_path)[1]) # format float values # green_df_copy['ENCL_DIAMETER_MM'] = green_df_copy['ENCL_DIAMETER_MM'].apply(lambda x: f"{x:.2f}") write_data(out_dir_path, image_path, green_df_copy, red_df_copy, other_df) print("Process completed successfully") print(str(len(green_df_copy)) + ' plaques were found\n')
async def handle(self, params, message, client): name = (params[0]) url = f'https://api.mojang.com/users/profiles/minecraft/{name}?' response = requests.get(url) uuid = response.json()['id'] data = requests.get(f"https://api.hypixel.net/player?key={settings.KEY}&name={name}").json() #if "player" in data == "null": # await message.channel.send("bad name") #else: try: if "rank" in data["player"] and data["player"]["rank"] != "NORMAL": rank = data["player"]["rank"] elif "newPackageRank" in data["player"]: rank = data["player"]["newPackageRank"] elif "packageRank" in data["player"]: rank = data["player"]["packageRank"] else: rank = "non" except TypeError: await message.channel.send("Player doesn't exist or has never played on hypixel") print("getting stats, please wait. ") #NameColor = (0,0,0) bwfinalkills = data["player"]["stats"]["Bedwars"]["final_kills_bedwars"] bwstars = data["player"]["achievements"]["bedwars_level"] displayname = data["player"]["displayname"] networkxp = data["player"]["networkExp"] skywarslevel = data["player"]["stats"]["SkyWars"]["levelFormatted"] xp = data["player"]["stats"]["SkyWars"]["skywars_experience"] print(rank) networkLevel = (math.sqrt((2 * networkxp) + 30625) / 50) - 2.5 networkLevel = round(networkLevel) def sw_xp_to_lvl(xp): xps = [0, 20, 70, 150, 250, 500, 1000, 2000, 3500, 6000, 10000, 15000] if xp >= 15000: return (xp - 15000) / 10000. + 12 else: for i in range(len(xps)): if xp < xps[i]: return i + float(xp - xps[i-1]) / (xps[i] - xps[i-1]) # skin = data2['value'] skinrender = f'https://crafatar.com/renders/head/{uuid}.png?size=64' #size doesnt work maybe the passte thing cana make t bigger print(skinrender) urllib.request.urlretrieve(skinrender, "skin.png") skin=Image.open('skin.png') # img = Image.new('RGB', (1920,1080), color = (255, 255, 255)) img2 = Image.open("darkbackground.jpg") enhancer = ImageEnhance.Brightness(img2) img2_output = enhancer.enhance(0.5) img2_output.save('darkbackground1.jpg') img2 = Image.open("darkbackground.jpg") #blurImage = img2.filter(ImageFilter.BLUR) #blurImage.save('blurbackground.png') img.paste(img2) img.paste(skin, (1800,0)) fnt = ImageFont.truetype('fonts/Minecraftia-Regular.ttf', 100) fnt2 = ImageFont.truetype('fonts/Minecraftia-Regular.ttf',70) d = ImageDraw.Draw(img) d.text((50,45), "Stats", font=fnt, fill=(255, 255, 255)) if displayname == "FinalHit": d.text((50,175), displayname, font=fnt2,fill=(211, 33, 255)) elif displayname == "sekoh": d.text((50,175), displayname, font=fnt2,fill=(255,85,85)) elif rank == "VIP": d.text((50,175), displayname, font=fnt2,fill=(255, 255, 85)) elif rank == "VIP_PLUS": d.text((50,175), displayname, font=fnt2,fill=(85, 255, 85)) elif rank == "MVP": d.text((50,175), displayname, font=fnt2,fill=(85, 255, 255)) elif rank == "MVP_PLUS": try: monthlyPackageRank = data["player"]["monthlyPackageRank"] print(monthlyPackageRank) if monthlyPackageRank == "SUPERSTAR": d.text((50,175), displayname, font=fnt2,fill=(255, 170, 0)) else: d.text((50,175), displayname, font=fnt2,fill=(85, 255, 255)) except KeyError: print("never got mvp++ before") d.text((50,175), displayname, font=fnt2,fill=(85, 255, 255)) #check if monthlypackagerank == superstar to see if mvp++ #d.text((50,150), displayname, font=fnt2,fill=(85, 255, 255)) elif rank == "YOUTUBER": d.text((50,175), displayname, font=fnt2,fill=(255, 85, 85)) elif rank == "ADMIN": d.text((50,175), displayname, font=fnt2,fill=(255, 85, 85)) elif rank == "HELPER": d.text((50,175), displayname, font=fnt2,fill=(85, 85, 255)) elif rank == "MODERATOR": d.text((50,175), displayname, font=fnt2,fill=(0, 170, 0)) else: rank = "NON" d.text((50,175), displayname, font=fnt2,fill=(170, 170, 170)) print(networkLevel) #d.text((50,175), networkLevel, font=fnt2,fill=(170, 170, 170)) hi = "hi" strnetworklevel = str(networkLevel) print(strnetworklevel) d.text((50,300), "hypixel level:", font=fnt2,fill=(255,255,255)) d.text((610 ,300), strnetworklevel, font=fnt2,fill=(255,255,255)) strbwstars = str(bwstars) print(strbwstars) d.text((50 ,370), "bedwars stars: ", font=fnt2,fill=(255,255,255)) d.text((710 ,370), strbwstars, font=fnt2,fill=(255,255,255)) strskywarslevel = str(skywarslevel) print(strskywarslevel) skywarslevels = sw_xp_to_lvl(xp) print(skywarslevels) roundskywarslevels = round(skywarslevels) strskywarslevels = str(roundskywarslevels) d.text((50 ,440), "skywars stars: ", font=fnt2,fill=(255,255,255)) d.text((710 ,440), strskywarslevels, font=fnt2,fill=(255,255,255)) #find skywars_experience and convert to level using #def sw_xp_to_lvl(xp): #xps = [0, 20, 70, 150, 250, 500, 1000, 2000, 3500, 6000, 10000, 15000] #if xp >= 15000: # return (xp - 15000) / 10000. + 12 #else: # for i in range(len(xps)): # if xp < xps[i]: # return i + float(xp - xps[i-1]) / (xps[i] - xps[i-1]) img.save('test.png') embed = discord.Embed( title = "Bedwars Finals", description = f'Bedwars final kills = {bwfinalkills}', colour = discord.Colour.red() ) embed.set_footer(text = f'message sent by {message.author.name}') # await message.channel.send(embed=embed) #await message.channel.send(skin) #await message.channel.send(bwfinalkills) await message.channel.send(file=discord.File('test.png')) print(networkxp) print(networkLevel) #settings.KEY
def random_brightness(img, factor): """random change the brightness of an img""" enhancer = ImageEnhance.Brightness(img) selector = np.random.uniform(low=factor) return enhancer.enhance(selector)
font = pygame.font.SysFont("Courier", 11) def disp(phrase, loc): s = font.render(phrase, True, (200, 200, 200)) sh = font.render(phrase, True, (50, 50, 50)) screen.blit(sh, (loc[0] + 1, loc[1] + 1)) screen.blit(s, loc) brightness = 1.0 contrast = 1.0 shots = 0 while 1: camshot = ImageEnhance.Brightness(cam.getImage()).enhance(brightness) camshot = ImageEnhance.Contrast(camshot).enhance(contrast) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() keyinput = pygame.key.get_pressed() if keyinput[K_1]: brightness -= .1 if keyinput[K_2]: brightness += .1 if keyinput[K_3]: contrast -= .1 if keyinput[K_4]: contrast += .1 if keyinput[K_q]: cam.displayCapturePinProperties() if keyinput[K_w]: cam.displayCaptureFilterProperties() #以下的代码,是在存一个抓图文件。文件名中使用了当前时间 if keyinput[K_s]: filename = str(time.time()) + ".jpg" cam.saveSnapshot(filename, quality=80, timestamp=0) shots += 1
def apply_brightness(image, value): enh = ImageEnhance.Brightness(image) return enh.enhance(value)
def bright(inpng, outpng, brightness): peak = Image.open(inpng) enhancer = ImageEnhance.Brightness(peak) bright = enhancer.enhance(brightness) bright.save(outpng)
def brightness(img, magnitude): magnitudes = np.linspace(0.1, 1.9, 11) img = ImageEnhance.Brightness(img).enhance( random.uniform(magnitudes[magnitude], magnitudes[magnitude + 1])) return img
def apply(self, image): return ImageEnhance.Brightness(image).enhance(self.level)
def __call__(self, image, *args): alpha = 1.0 + np.random.uniform(-self.var, self.var) image = ImageEnhance.Brightness(image).enhance(alpha) return (image, *args)
def random_brightness(img, lower=0.5, upper=1.5): e = random.uniform(lower, upper) return ImageEnhance.Brightness(img).enhance(e)
def __get_more_img(self, img_path): im_name = os.path.splitext(os.path.split(img_path)[1])[0] im_name = im_name.replace('_pig', '') file_no = 0 self.__cal_progress(im_name) # 输出进度 origin_image = Image.open(img_path) # 生成猪的原图 image, pos = self.__get_pig_object(origin_image) image.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) if pos[1] - pos[0] < 50 or pos[3] - pos[2] < 50: return # 生成能用最小的框框住猪的原图(带背景) file_no += 1 frame_img = Image.open(os.path.join(os.path.split(img_path)[0], '%s.jpg' % im_name)) np_frame_img = np.array(frame_img.resize(self.RESIZE_SIZE)) np_frame_img = np_frame_img[pos[0]: pos[1] + 1, pos[2]: pos[3] + 1] new_frame_img = Image.fromarray(np_frame_img) new_frame_img.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 水平翻转 file_no += 1 flip_image = image.transpose(Image.FLIP_LEFT_RIGHT) flip_image.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 垂直翻转 file_no += 1 flip_image = image.transpose(Image.FLIP_TOP_BOTTOM) flip_image.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 亮度 brightness_up = 1 + random.random() * 0.8 brightness_down = 1 - random.random() * 0.85 enh_bri = ImageEnhance.Brightness(image) # 亮度增强 file_no += 1 image_brightened = enh_bri.enhance(brightness_up) image_brightened.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 亮度降低 file_no += 1 image_brightened = enh_bri.enhance(brightness_down) image_brightened.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 色度 color_up = 1 + random.random() * 0.8 color_down = 1 - random.random() * 0.7 enh_col = ImageEnhance.Color(image) # 色度增强 file_no += 1 image_colored = enh_col.enhance(color_up) image_colored.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 色度降低 file_no += 1 image_colored = enh_col.enhance(color_down) image_colored.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 对比度 contrast_up = 1 + random.random() * 0.55 contrast_down = 1 - random.random() * 0.5 enh_con = ImageEnhance.Contrast(image) # 对比度增强 file_no += 1 image_contrasted = enh_con.enhance(contrast_up) image_contrasted.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 对比度降低 file_no += 1 image_contrasted = enh_con.enhance(contrast_down) image_contrasted.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 锐度 sharpness_up = 1 + random.random() * 2 sharpness_down = 1 - random.random() * 0.8 enh_sha = ImageEnhance.Sharpness(image) # 锐度增强 file_no += 1 image_sharped = enh_sha.enhance(sharpness_up) image_sharped.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 锐度降低 file_no += 1 image_sharped = enh_sha.enhance(sharpness_down) image_sharped.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 遮挡 np_image = np.array(image) for i in range(self.NUM_BLOCK_IMAGE): block_image = Image.fromarray(self.__get_block_img(copy.deepcopy(np_image))) file_no += 1 block_image.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no))) # 随机裁剪图片 for i in range(self.NUM_CORP_IMAGE): corp_image = self.__random_corp(np_image) file_no += 1 corp_image.save(os.path.join(self.IMG_MORE_PATH, '%s_%d.jpg' % (im_name, file_no)))
# A task that is fairly common in image and picture manipulation is to create contact sheets of images. # A contact sheet is one image that actually contains several other different images. Lets try and make # a contact sheet for the Master of Science in Information advertisment image. In particular, lets change # the brightness of the image in ten different ways, then scale the image down smaller, and put them side # by side so we can get the sense of which brightness we might want to use. # # First up, lets import the ImageEnhance module, which has a nice object called Brightness from PIL import ImageEnhance # Checking the online documentation for this function, it takes a value between 0.0 (a completely black # image) and 1.0 (the original image) to adjust the brightness. All of the classes in the ImageEnhance module # do this the same way, you create an object, in this case Brightness, then you call the enhance function() # on that object with an appropriate parameter. # # Lets write a little loop to generate ten images of different brightness. First we need the Brightness # object with our image enhancer = ImageEnhance.Brightness(image) images = [] for i in range(0, 10): # We'll divide i by ten to get the decimal value we want, and append it to the images list # we actually call the brightness routine by calling the enhance() function. Remember, you can dig into # details of this using the help() function, or by consulting web docs images.append(enhancer.enhance(i / 10)) # We can see the result here is a list of ten PIL.Image.Image objects. Jupyter nicely prints out the value # of python objects nested in lists print(images) # In[ ]: # Lets take these images now and composite them, one above another, in a contact sheet. # There are several different approaches we can use, but I'll simply create a new image which is like # the first image, but ten times as high. Lets check out the PIL.Image.new functionality
def brightness(self, factor): _img = self._read_image() if _img is not None: from PIL import ImageEnhance _img = ImageEnhance.Brightness(_img).enhance(factor) self.store_graphic(_img, self.content_type, self.image_name)