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
python类Brightness()的实例源码
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)
repositoryimage.py 文件源码
项目:RobotframeworkAuto-for-PEP_PRO
作者: xiaoyaojjian
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
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 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