我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用PIL.ImageEnhance.Brightness()。
def velocity_ocr(image,coords,f1app): # crop and convert image to greyscale img = Image.fromarray(image).crop(coords).convert('L') img = img.resize([img.width*2,img.height*2]) if f1app: # filters for video from the f1 app img = ImageEnhance.Brightness(img).enhance(3.0) img = ImageEnhance.Contrast(img).enhance(2.0) else: # filters for onboard video graphic img = ImageEnhance.Brightness(img).enhance(0.1) img = ImageEnhance.Contrast(img).enhance(2.0) img = ImageEnhance.Contrast(img).enhance(4.0) img = ImageEnhance.Brightness(img).enhance(0.2) img = ImageEnhance.Contrast(img).enhance(16.0) try: # vel = pytesseract.image_to_string(img,config='digits') vel = pytesseract.image_to_string(img) except UnicodeDecodeError: vel = -1 return vel
def maskFace(self, frame_image, face): img1 = cv2.imread(self.__class__.mask_path, cv2.IMREAD_UNCHANGED); elements = cv2.imread(self.__class__.mask_elements_path, cv2.IMREAD_UNCHANGED); h, status = cv2.findHomography(self.average_points, np.array(self.getFacePoints(face))) mask = self.getTransPIL(cv2.warpPerspective(img1, h, (frame_image.width,frame_image.height))) mask_elements = self.getTransPIL(cv2.warpPerspective(elements, h, (frame_image.width,frame_image.height))) enhancer = ImageEnhance.Color(frame_image) enhanced = enhancer.enhance(0.1) enhancer = ImageEnhance.Brightness(enhanced) enhanced = enhancer.enhance(1.2) enhancer = ImageEnhance.Contrast(enhanced) enhanced = enhancer.enhance(1.2) frame_image.paste(enhanced, (0,0), mask) frame_image.paste(mask_elements, (0,0), mask_elements)
def enhance(image, func, *args, **kwargs): """ Enhance image using a PIL enhance function See the following link for details on PIL enhance functions: http://pillow.readthedocs.io/en/3.1.x/reference/ImageEnhance.html >>> from PIL.ImageEnhance import Brightness >>> image = np.ones((3,2), dtype='uint8') >>> enhance(image, Brightness, 0.0) array([[0, 0], [0, 0], [0, 0]], dtype=uint8) :param numpy array image: Numpy array with range [0,255] and dtype 'uint8'. :param function func: PIL ImageEnhance function :param args args: Argument list passed on to enhance function. :param kwargs kwargs: Key-word arguments passed on to enhance function :return: Enhanced image :rtype: numpy array with range [0,255] and dtype 'uint8' """ image = arr_to_pil(image) image = func(image).enhance(*args, **kwargs) return pil_to_arr(image)
def change_brightness(image, brightness=1.0): """ Change brightness of image. >>> image = np.eye(3, dtype='uint8') * 255 >>> change_brightness(image, 0.5) array([[127, 0, 0], [ 0, 127, 0], [ 0, 0, 127]], dtype=uint8) See http://pillow.readthedocs.io/en/3.1.x/reference/ImageEnhance.html#PIL.ImageEnhance.Brightness :param numpy array image: Numpy array with range [0,255] and dtype 'uint8'. :param float brightness: Brightness [0, 1] :return: Image with changed brightness :rtype: numpy array with range [0,255] and dtype 'uint8' """ return enhance(image, ie.Brightness, brightness)
def img(self, Local_initial_address, i, local_store_address): print Local_initial_address, i, local_store_address # tt = u'lvziqing' im = Image.open(Local_initial_address) text = time.ctime() width, height = im.size print width, height txt = Image.new('RGB', im.size, (0, 0, 0, 0)) text_width = (txt.size[0] - 280) text_height = (txt.size[1] - 130) # watermark = txt.resize((text_width,text_height), Image.ANTIALIAS) draw = ImageDraw.Draw(txt, 'RGBA') # ??????? draw.text((text_width, text_height), text, fill=(255,255,255)) watermark = txt.rotate(23, Image.BICUBIC) alpha = watermark.split()[2] alpha = ImageEnhance.Brightness(alpha).enhance(0.50) watermark.putalpha(alpha) a = local_store_address + 'ceshi' + str(i) + '.jpg' Image.composite(watermark, im, watermark).save(a, 'JPEG') return a
def brightness_transform(img, brightness_min=0.93, brightness_max=1.4): """Transform input image brightness Transform the input image brightness by a factor returned by a unifrom distribution with `brightness_min` and `brightness_max` as params Args: img: `ndarray`, input image brightness_min: float, minimum contrast for transformation brightness_max: float, maximum contrast for transformation Returns: `ndarray`, brightness transformed image """ if isinstance(img, (np.ndarray)): img = Image.fromarray(img) brightness_param = np.random.uniform(brightness_min, brightness_max) t_img = ImageEnhance.Brightness(img).enhance(brightness_param) return np.array(t_img)
def lomoize (image,darkness,saturation): (width,height) = image.size max = width if height > width: max = height mask = Image.open("./lomolive/lomomask.jpg").resize((max,max)) left = round((max - width) / 2) upper = round((max - height) / 2) mask = mask.crop((left,upper,left+width,upper + height)) # mask = Image.open('mask_l.png') darker = ImageEnhance.Brightness(image).enhance(darkness) saturated = ImageEnhance.Color(image).enhance(saturation) lomoized = Image.composite(saturated,darker,mask) return lomoized
def produce(txt,img,ver=5,err_crt = qrcode.constants.ERROR_CORRECT_H,bri = 1.0, cont = 1.0,\ colourful = False, rgba = (0,0,0,255),pixelate = False): """Produce QR code :txt: QR text :img: Image path / Image object :ver: QR version :err_crt: QR error correct :bri: Brightness enhance :cont: Contrast enhance :colourful: If colourful mode :rgba: color to replace black :pixelate: pixelate :returns: list of produced image """ if type(img) is Image.Image: pass elif type(img) is str: img = Image.open(img) else: return [] frames = [produce_impl(txt,frame.copy(),ver,err_crt,bri,cont,colourful,rgba,pixelate) for frame in ImageSequence.Iterator(img)] return frames
def adjust_brightness(image): #Find brightness of image temp = image.convert('L') stat = ImageStat.Stat(temp) brightness = (stat.mean[0]/255) #Think this makes more sense enhancer = ImageEnhance.Brightness(image) if brightness > 0.10: image = enhancer.enhance(1.10-brightness) """ if brightness > 0.35: image = enhancer.enhance(0.75) elif brightness > 0.60: image = enhancer.enhance(0.50) """ return image #Now take the segments and organize them to be drawn on the image
def getJitteredImgs(self, img, num, maxRot=(-5.0, 5.0), maxTranslate=(-2.0, 2.0), maxScale=(-0.1, 0.1), augmentColor=False): """ Take img and jitter it :return: a list of all jittered images """ cx = img.size[0] / 2 cy = img.size[1] / 2 tMats = self.getJitteredParams(center=(cx, cy), num=num, maxRot=maxRot, maxTranslate=maxTranslate, maxScale=maxScale) imgs = [] for i in range(len(tMats)): t = tMats[i] imgT = self.transformImg(img, t) if augmentColor: # jitter colors color = ImageEnhance.Color(imgT) imgT = color.enhance(self.rng.uniform(0.7, 1)) # jitter contrast contr = ImageEnhance.Contrast(imgT) imgT = contr.enhance(self.rng.uniform(0.7, 1)) # jitter brightness bright = ImageEnhance.Brightness(imgT) imgT = bright.enhance(self.rng.uniform(0.7, 1)) # add noise im = numpy.asarray(imgT).astype('int') + numpy.rint(self.rng.normal(0, 4, numpy.asarray(imgT).shape)).astype('int') im = numpy.clip(im, 0, 255).astype('uint8') imgT = Image.fromarray(im) # add image imgs.append(imgT) return imgs, tMats
def preprocess(self, image, action): # Luminance Manipulation brightness = ImageEnhance.Brightness(image) image_pro = brightness.enhance(action) return image_pro
def do_brightness(self): """usage: brightness <image:pic1> Enhance brightness in the top image. """ from PIL import ImageEnhance factor = float(self.do_pop()) image = self.do_pop() enhancer = ImageEnhance.Brightness(image) self.push(enhancer.enhance(factor))
def reduce_opacity(im, opacity): """Returns an image with reduced opacity.""" assert opacity >= 0 and opacity <= 1 if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) return im
def random_bright_shift(arr, tf): img = to_PIL(arr, tf) if tf: return ImageEnhance.Brightness(img).enhance(np.random.uniform(0.8, 1.2)) return to_theano(ImageEnhance.Brightness(img).enhance(np.random.uniform(0.8, 1.2)))
def change_brightness(img, level): """ Increase the brightness of an image :param img: PIL image object :param level: Adjust brightness (int) :return: PIL image object """ brightness = ImageEnhance.Brightness(img) return brightness.enhance(level)
def test_enhance(): image = np.ones((5, 4), dtype='uint8') expected = np.zeros((5, 4), dtype='uint8') enhanced = ni.enhance(image, ie.Brightness, 0.0) nt.assert_allclose(expected, enhanced) assert enhanced.dtype == np.uint8
def test_draw_on_image_with_enhancements(self, _draw_content_mock, _save, enhance_mock): with create_test_image(): enhance_mock.return_value = PIL_Image.open('test.png') self.img.draw_on_image( image_path=os.path.abspath('test.png'), image_enhancements=((ImageEnhance.Sharpness, 0.5), (ImageEnhance.Brightness, 0.5))) self.assertTrue(enhance_mock.called) self.assertTrue(_draw_content_mock.called)
def set_opacity(im, opacity): """?????""" assert opacity >=0 and opacity < 1 if im.mode != "RGBA": im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) return im
def brightness_enhance(self, factor, new_path=None, is_show=False): if self.img is None: img = Image.open(self.path) else: img = self.img img = ImageEnhance.Brightness(img).enhance(factor) if new_path is not None: img.save(new_path) if is_show: img.show(title='brightness') return img
def brightness(func_config): def f(image_config): factor = random.random() * (func_config.max_factor - func_config.min_factor) + func_config.min_factor factor = misc.uniform_sample_from_interval(func_config.min_factor, func_config.max_factor) image_config.image = ImageEnhance.Brightness(image_config.image).enhance(factor) return f
def make_bright_img(file_name, path_dir): file_path = path_dir + '/' + file_name img = Image.open('%s' % file_path) ImageEnhance.Brightness(img).enhance(1.5).save(path_dir + '/' + '%02s_dim' % file_name.translate(None, '.png') + '.png', "PNG") return
def inkwell(image): # copy = grayscale(image) # enhancer = ImageEnhance.Contrast(copy) # enhancer.enhance(1.1) # enhancer = ImageEnhance.Brightness(copy) # enhancer.enhance(1.1) return image
def nss(image): size = image.size nss = Image.new('RGBA', size, (243, 106, 188, 77)) enhancer = ImageEnhance.Contrast(nss) enhancer.enhance(1.1) enhancer = ImageEnhance.Brightness(nss) enhancer.enhance(1.1) enhancer = ImageEnhance.Color(nss) enhancer.enhance(1.3) copy = image.copy() copy.paste(nss, (0, 0), nss) return copy
def call(self, img): if img is None: raise ValueError('img is None') im_n = img.copy() r = random() contrast_low, contrast_high = 0, self.contrast brightness_low, brightness_high = contrast_high, contrast_high + self.brightness sharpness_low, sharpness_high = brightness_high, brightness_high + self.sharpness color_low, color_high = sharpness_high, sharpness_high + self.color if contrast_low <= r < contrast_high: factor_contrast = randint(5, 10)/10 enhancer = ImageEnhance.Contrast(im_n) im_n = enhancer.enhance(factor_contrast) elif brightness_low <= r < brightness_high: factor_brightness = randint(5, 15)/10 enhancer = ImageEnhance.Brightness(im_n) im_n = enhancer.enhance(factor_brightness) elif sharpness_low <= r < sharpness_high: factor_sharpen = randint(0, 20)/10 enhancer = ImageEnhance.Sharpness(im_n) im_n = enhancer.enhance(factor_sharpen) elif color_low <= r < color_high: factor_color = randint(0, 20)/10 enhancer = ImageEnhance.Color(im_n) im_n = enhancer.enhance(factor_color) else: pass return im_n
def randomColor(image): """ ????????? :param image: PIL???image :return: ????????image """ random_factor = np.random.randint(0, 31) / 10. # ???? color_image = ImageEnhance.Color(image).enhance(random_factor) # ???????? random_factor = np.random.randint(10, 21) / 10. # ???? brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor) # ??????? random_factor = np.random.randint(10, 21) / 10. # ???1? contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor) # ??????? random_factor = np.random.randint(0, 31) / 10. # ???? return ImageEnhance.Sharpness(contrast_image).enhance(random_factor) # ??????
def bright(inpng, outpng, brightness): peak = Image.open(inpng) enhancer = ImageEnhance.Brightness(peak) bright = enhancer.enhance(brightness) bright.save(outpng)
def tesseract(self, img): # keep the data fileName = "tmp_"+int(time.time()+random.randint(1,99999)).__str__()+".jpeg" while os.path.exists( fileName ): fileName = "tmp_"+int(time.time()+random.randint(1,99999)).__str__()+".jpeg" self.tmp_file = fileName with open(self.tmp_file, "w") as oFd: oFd.write(img) # resolve noise try: im = Image.open(self.tmp_file) enhancer = ImageEnhance.Color(im) im = enhancer.enhance(0.0) enhancer = ImageEnhance.Contrast(im) im = enhancer.enhance(3.0) enhancer = ImageEnhance.Brightness(im) im = enhancer.enhance(10.0) enhancer = ImageEnhance.Contrast(im) im = enhancer.enhance(20.0) enhancer = ImageEnhance.Sharpness(im) im = enhancer.enhance(0.0) im.save(self.tmp_file) except Exception as e: pass else: pass # use tesseract imgCode = os.popen("tesseract -l eng -psm 8 {} stdout 2>/dev/null"\ .format(self.tmp_file)).readline()[0:-1] log.debug("Guess Ratio:{}/{}={}%".format(self.guess_hit+1, self.guess_total, \ ((self.guess_hit+1)*100/(self.guess_total)))) os.remove( self.tmp_file ) return imgCode
def TF_enhance_brightness(x, p=1.0): assert len(x.shape) == 3 h, w, nc = x.shape enhancer = ImageEnhance.Brightness(np_to_pil(x)) return pil_to_np(enhancer.enhance(p))
def lens_blur(input_path, depthmap_path, min_focal, max_focal, transition, radius, brightness, output_dir, speed=1): """ lens blur """ im = Image.open(input_path) im.load() format = im.format depthmap = Image.open(depthmap_path) depth_px = depthmap.load() power = 10 ** brightness speed = int(min(speed, im.width, im.height)) # prepare gradient filters and filtered images gradient_filters = [] filtered_images = [] copy_box = (0, 0, im.width, im.height) for i in range(radius): gradient_filters.append(ImageFilter.GaussianBlur(1)) image_i = im.crop(copy_box) for j in range(i): image_i = image_i.filter(gradient_filters[i]) filtered_images.append(image_i) # manipulate pixel for i in range(0, im.width, speed): for j in range(0, im.height, speed): depth = depth_px[i,j][0] box = (i, j, i + speed, j + speed) pixel = im.crop(box) if depth - max_focal >= transition or min_focal - depth >= transition: pixel = filtered_images[radius - 1].crop(box) elif depth - max_focal > 0: pixel = filtered_images[int((depth - max_focal)/transition*radius) - 1].crop(box) elif min_focal - depth > 0: pixel = filtered_images[int((min_focal - depth)/transition*radius) - 1].crop(box) im.paste(pixel, box) # output image enhancer = ImageEnhance.Brightness(im) im = enhancer.enhance(power) name = hex(int(time.time() * 100000))[2:] path = output_dir + '/' + str(name) + '.' + format im.save(path) return path
def variation_watermark(image, **wm_settings): """ ????????? ???????? ????? ?? ???????? """ if image.mode != 'RGBA': image = image.convert('RGBA') with open(wm_settings['file'], 'rb') as fp: watermark = Image.open(fp) info = watermark.info if watermark.mode not in ('RGBA', 'LA') and not (watermark.mode == 'P' and 'transparency' in info): watermark.putalpha(255) img_width, img_height = image.size wm_width, wm_height = watermark.size scale = wm_settings['scale'] if scale != 1: watermark = watermark.resize((int(wm_width * scale), int(wm_height * scale)), Image.ANTIALIAS) wm_width, wm_height = watermark.size position = wm_settings['position'] padding = wm_settings['padding'] if position == 'TL': left = padding[0] top = padding[1] elif position == 'TR': left = img_width - wm_width - padding[0] top = padding[1] elif position == 'BL': left = padding[0] top = img_height - wm_height - padding[1] elif position == 'BR': left = img_width - wm_width - padding[0] top = img_height - wm_height - padding[1] elif position == 'C': top = (img_height - wm_height) // 2 left = (img_width - wm_width) // 2 else: left = top = padding opacity = wm_settings['opacity'] if opacity < 1: alpha = watermark.convert('RGBA').split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) watermark.putalpha(alpha) image.paste(watermark, (left, top), watermark) return image
def _draw_watermark(self): '''Draws a watermark on the image''' watermark_image = PIL_Image.new('RGBA', self.image.size, (0, 0, 0, 0)) self.watermark._adjust_fontsize(self.image) draw = ImageDraw.Draw(watermark_image, 'RGBA') w_width, w_height = self.watermark.font.getsize(self.watermark.text) draw.text(((watermark_image.size[0] - w_width) / 2, (watermark_image.size[1] - w_height) / 2), self.watermark.text, font=self.watermark.font, fill=self.watermark.color) if self.watermark.rotate_angle: watermark_image = watermark_image.rotate( self.watermark.rotate_angle, PIL_Image.BICUBIC) alpha = watermark_image.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(self.watermark.opacity) watermark_image.putalpha(alpha) # Because watermark can be rotated we create a separate image for cross # so that it doesn't get rotated also. + It's impossible to drawn # on a rotated image if self.watermark.cross: watermark_cross_image = PIL_Image.new( 'RGBA', self.image.size, (0, 0, 0, 0)) cross_draw = ImageDraw.Draw(watermark_cross_image, 'RGBA') line_width = 1 + int(sum(self.image.size) / 2 * 0.007) cross_draw.line( (0, 0) + watermark_image.size, fill=self.watermark.color, width=line_width ) cross_draw.line( (0, watermark_image.size[1], watermark_image.size[0], 0), fill=self.watermark.color, width=line_width ) watermark_cross_alpha = watermark_cross_image.split()[3] watermark_cross_alpha = ImageEnhance.Brightness( watermark_cross_alpha).enhance(self.watermark.opacity) watermark_cross_image.putalpha(watermark_cross_alpha) # Adds cross to the watermark watermark_image = PIL_Image.composite( watermark_cross_image, watermark_image, watermark_cross_image) self.image = PIL_Image.composite( watermark_image, self.image, watermark_image)
def gen_pic(MediaId): pic = Image.open('media/' + MediaId).convert('LA') # pic = ImageEnhance.Brightness(pic).enhance(0.35) portion = pic.size[0]/pic.size[1] if portion < 1: #portrait if portion <= 0.75: pic_w = 960 pic_h = round(960/portion) box = (0,round((pic_h-1280)/2),960,round(pic_h/2+640)) if portion > 0.75: pic_h = 1280 pic_w = round(1280*portion) box = (round((pic_w-960)/2),0,round(pic_w/2+480),1280) layer = Image.open('./lomolive/layer_p.png') elif portion > 1: #landscape if portion >= 1.3333: pic_h = 960 pic_w = round(960*portion) box = (round((pic_w-1280)/2),0,round(pic_w/2+640),960) if portion < 1.3333: pic_w = 1280 pic_h = round(1280/portion) box = (0,round((pic_h-960)/2),1280,round(pic_h/2+480)) layer = Image.open('./lomolive/layer_l.png') elif portion == 1: #square (pic_w,pic_h) = (960,960) box = (0,0,960,960) layer = Image.open('./lomolive/layer_s.png') pic = pic.resize((pic_w, pic_h)) pic = pic.crop(box) pic = lomoize(pic, 0.4, 1) pic = pic.convert('RGB') pic.paste(layer,(0,0),layer) pic.save('media/' + MediaId + '.jpg', quality=95)
def main(): import argparse parser = argparse.ArgumentParser(description="Combine your QR code with custom picture") parser.add_argument("image") parser.add_argument("text", help="QRcode Text.") parser.add_argument("-o", "--output", help="Name of output file.") parser.add_argument("-v", "--version", type=int, help="QR version.In range of [1-40]") parser.add_argument("-e", "--errorcorrect", choices={"L","M","Q","H"}, help="Error correct") parser.add_argument("-b", "--brightness", type=float, help="Brightness enhance") parser.add_argument("-c", "--contrast", type=float, help="Contrast enhance") parser.add_argument("-C", "--colourful", action="store_true",help="colourful mode") parser.add_argument("-r", "--rgba", nargs=4, metavar=('R','G','B','A'),type = int, help="color to replace black") parser.add_argument("-p", "--pixelate", action="store_true",help="pixelate") args = parser.parse_args() img = args.image txt = args.text output = args.output if args.output else 'qr.png' ec = qrcode.constants.ERROR_CORRECT_H if args.errorcorrect: ec_raw = args.errorcorrect if ec_raw == 'L': ec = qrcode.constants.ERROR_CORRECT_L if ec_raw == 'M': ec = qrcode.constants.ERROR_CORRECT_M if ec_raw == 'Q': ec = qrcode.constants.ERROR_CORRECT_Q ver = 5 if args.version: if args.version >= 1 and args.version <= 40: ver = args.version cont = args.contrast if args.contrast else 1.0 bri = args.brightness if args.brightness else 1.0 colr = True if args.colourful else False pixelate = True if args.pixelate else False if colr : if args.rgba: rgba = tuple(args.rgba) else: rgba = (0,0,0,255) else: rgba = (0,0,0,255) frames = produce(txt,img,ver,ec,bri, cont ,colourful = colr,rgba=rgba,pixelate = pixelate) if len(frames) == 1 or output.upper()[-3:] != "GIF": frames[0].save(output) elif len(frames) > 1: frames[0].save(output,save_all=True,append_images=frames[1:],duration=100,optimize=True)