Ejemplo n.º 1
0
def convertToGreyscale(img):

    return ImageEnhance.Contrast(img).enhance(50.0)
Ejemplo n.º 2
0
def color(im, k=3):
    enhancer = ImageEnhance.Color(im)
    return enhancer.enhance(k)
Ejemplo n.º 3
0
def sharpness(im, k=3):
    enhancer = ImageEnhance.Sharpness(im)
    return enhancer.enhance(k)
Ejemplo n.º 4
0
    #if not cap.isOpened():
    #    print('failed to open stream')
    #    break
    if not cap_inf.isOpened():
        print('failed to open inf stream')

    #ret, frame = cap.read()
    ret_inf, inf_frame = cap_inf.read()

    inf_tmp = inf_frame

    #inf_cvt = cv2.cvtColor(inf_frame, cv2.COLOR_BGR2RGB)
    #print(type(inf_frame))
    #print(np.asarray(inf_frame).shape)
    inf_frame = Image.fromarray(inf_frame)
    enb = ImageEnhance.Contrast(inf_frame)
    inf_frame = enb.enhance(1)

    enb = ImageEnhance.Color(inf_frame)
    inf_frame = enb.enhance(4)

    enb = ImageEnhance.Sharpness(inf_frame)
    inf_frame = enb.enhance(8)

    #inf_frame = cv2.cvtColor(np.asarray(inf_frame),cv2.COLOR_RGB2BGR)

    inf_frame = np.asarray(inf_frame)

    if is_conv == 1:
        inf_frame = conv_color - inf_frame
Ejemplo n.º 5
0
 def __call__(self, img):
     enhancer = ImageEnhance.Brightness(img)
     return enhancer.enhance(self.factor)
Ejemplo n.º 6
0
 def scale_colors(self, image=False, degree=0.5):
     image = image if image else self.image
     return Imager(image=ImageEnhance.Color(image).enhance(degree))
Ejemplo n.º 7
0
hea = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'
}
url = "http://hd.hinews.cn/2/checkcode.php"

for i in range(1, 5):
    html = requests.get(url, headers=hea, timeout=60).content
    fp = open("pic.jpg", 'wb')
    fp.write(html)
    fp.close()

    im = Image.open("pic.jpg")
    im.show()

    im = ImageEnhance.Sharpness(im).enhance(2)
    enhancer = ImageEnhance.Contrast(im)
    im = enhancer.enhance(5)
    im = im.convert("1")
    im = im.filter(ImageFilter.ModeFilter(2))

    final_pic = im
    final_pic.show()
    strabc = pytesseract.image_to_string(final_pic)
    print(strabc)
'''    
    im = Image.open("pic.jpg")
    im.show()
    im = ImageEnhance.Sharpness(im).enhance(3)
    im.show()
    enhancer = ImageEnhance.Contrast(im)
Ejemplo n.º 8
0
imgsrc = driver.find_element_by_id("captcha").get_attribute('src')
print(imgsrc)
screenImg = r"C:\Users\Administrator\Desktop\screenImg.png"
driver.get_screenshot_as_file(screenImg)
#获取验证码的位置
location = driver.find_element_by_id("captcha").location
#获取验证码size
size = driver.find_element_by_id("captcha").size
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
print(left, top, right, bottom)
img = Image.open(screenImg).crop((left, top, right, bottom))
img = img.convert('L')  #转换模式:L | RGB
img = ImageEnhance.Contrast(img)  #增强对比度
img = img.enhance(2.0)  #增加饱和度
img.save(screenImg)
print("验证码保存成功")
img = Image.open(screenImg)
code = pytesseract.image_to_string(img)
print(code)
#code= pytesser.image_file_to_string(screenImg)
#driver.find_element_by_id("captcha").send_keys(code.strip())
print("ok")
#输入账号,密码登录
driver.find_element_by_id("username").send_keys("guanliyuan")
driver.find_element_by_id("password").send_keys("youjian@2018")
driver.find_element_by_id("checkCode").send_keys(code)
#验证码识别错误手动填写
time.sleep(5)
Ejemplo n.º 9
0
async def arcb30init(kwargs):
    cache = os.path.abspath('./cache')
    assets_apk = os.path.abspath('./assets/arc.apk')
    if not os.path.exists(assets_apk):
        await sendMessage(kwargs, '未找到arc.apk!')
        return
    assets = os.path.abspath('./assets/arcaea')
    if os.path.exists(assets):
        shutil.rmtree(assets)
    os.mkdir(assets)
    if zipfile.is_zipfile(assets_apk):
        fz = zipfile.ZipFile(assets_apk, 'r')
        for file in fz.namelist():
            fz.extract(file, cache)
    copysongpath = cache + '/assets/songs'
    songdirs = os.listdir(copysongpath)
    for file in songdirs:
        filename = os.path.abspath(f'{copysongpath}/{file}')
        if os.path.isdir(filename):
            output = os.path.abspath('./cache/songoutput/')
            if not os.path.exists(output):
                os.makedirs(output)
            file = re.sub('dl_', '', file)
            filename = filename + '/base.jpg'
            if os.path.exists(filename):
                shutil.copy(filename, f'{output}/{file}.jpg')

    files = os.listdir(output)
    outputpath = os.path.abspath('./cache/bluroutput')
    if not os.path.exists(outputpath):
        os.makedirs(outputpath)

    for file in files:
        img = Image.open(f'{output}/{file}')
        img2 = img.filter(ImageFilter.GaussianBlur(radius=2))
        downlight = ImageEnhance.Brightness(img2)
        d2 = downlight.enhance(0.65)
        if not os.path.exists(outputpath):
            os.makedirs(outputpath)
        d2.save(f'{outputpath}/{file}')

    files = os.listdir(outputpath)
    songimgdir = assets + '/songimg'
    if not os.path.exists(songimgdir):
        os.makedirs(songimgdir)

    for file in files:
        img = Image.open(os.path.abspath(f'{outputpath}/{file}'))
        img1 = img.resize((325, 325))
        img2 = img1.crop((0, 62, 325, 263))
        img2.save(os.path.abspath(f'{songimgdir}/{file}'))

    shutil.copytree(cache + '/assets/char', assets + '/char')
    shutil.copytree(cache + '/assets/Fonts', assets + '/Fonts')
    ratings = ['0', '1', '2', '3', '4', '5', '6', 'off']
    os.mkdir(assets + f'/ptt/')
    for rating in ratings:
        shutil.copy(cache + f'/assets/img/rating_{rating}.png',
                    assets + f'/ptt/rating_{rating}.png')

    worldimg = cache + f'/assets/img/world'
    worldimglist = os.listdir(worldimg)
    os.mkdir(assets + f'/world/')
    for x in worldimglist:
        if x.find('_') == -1:
            shutil.copy(cache + f'/assets/img/world/{x}',
                        assets + f'/world/{x}')

    coordinate = {
        'left_top': [1070, 25],
        'right_top': [1070, 25],
        'right_bottom': [1070, 959],
        'left_bottom': [134, 959]
    }
    rotate = Rotate(Image.open(cache + '/assets/img/scenery/bg_triangle.png'),
                    coordinate)
    rotate.run().convert('RGBA').save(assets + '/triangle.png')
    cardoverlay = Image.open(
        os.path.abspath(
            f'{cache}/assets/layouts/mainmenu/card/card_overlay.png'))
    cropoverlay = cardoverlay.crop((56, 307, 971, 377))
    cropoverlay.save(os.path.abspath(f'{assets}/card_overlay.png'))
    difficult = ['0', '1', '2', '3']
    for ds in difficult:
        d = Image.open(
            os.path.abspath(f'{cache}/assets/img/cutoff_dia_{ds}.png'))
        cd = d.crop((0, 0, 47, 47))
        cd = cd.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
        cd.save(os.path.abspath(f'{assets}/{ds}.png'))

    await sendMessage(kwargs, '成功初始化!')
 def __call__(self, img):
     alpha = random.uniform(1 - self.var, 1 + self.var)
     return ie.Contrast(img).enhance(alpha)
 def __call__(self, img):
     alpha = random.uniform(1 - self.var, 1 + self.var)
     return ie.Sharpness(img).enhance(alpha)
Ejemplo n.º 12
0
    def wizard_image(svg_image, operations):
        image = svg_image.image
        matrix = Matrix(svg_image.transform)
        step = None
        from PIL import Image, ImageOps, ImageFilter, ImageEnhance
        try:
            alpha_mask = image.getchannel('A')
        except ValueError:
            alpha_mask = None
        empty_mask = None
        for op in 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 == 'resample':
                try:
                    if op['enable']:
                        image, matrix = RasterScripts.actualize(
                            image, matrix, step_level=op['step'])
                        step = op['step']
                        if alpha_mask is not None:
                            alpha_mask = image.getchannel('A')
                            # Get the resized alpha mask.
                        empty_mask = None
                except KeyError:
                    pass
            elif name == 'grayscale':
                try:
                    if op['enable']:
                        try:
                            r = op['red'] * 0.299
                            g = op['green'] * 0.587
                            b = op['blue'] * 0.114
                            v = op['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 op['invert']:
                                empty_mask = image.point(lambda e: 0
                                                         if e == 0 else 255)
                                image = ImageOps.invert(image)
                            else:
                                empty_mask = image.point(lambda e: 0
                                                         if e == 255 else 255)
                        except (KeyError, OSError):
                            pass

                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 != 'P':
                            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 = RasterScripts.spline(tone_values)
                            else:
                                tone_values = [
                                    q for q in tone_values if q is not None
                                ]
                                spline = RasterScripts.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 == 'dither':
                try:
                    if alpha_mask is not None:
                        background = Image.new(image.mode, image.size, 'white')
                        background.paste(image, mask=alpha_mask)
                        image = background  # Mask exists use it to remove any pixels that were pure reject.
                        alpha_mask = None
                    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.
                        empty_mask = None
                    if op['enable'] and op['type'] is not None:
                        if image.mode == 'RGBA':
                            pixel_data = image.load()
                            width, height = image.size
                            for y in range(height):
                                for x in range(width):
                                    if pixel_data[x, y][3] == 0:
                                        pixel_data[x, y] = (255, 255, 255, 255)
                        image = image.convert("1")
                except KeyError:
                    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 alpha_mask is not None:
            background = Image.new(image.mode, image.size, 'white')
            background.paste(image, mask=alpha_mask)
            image = background  # Mask exists use it to remove any pixels that were pure reject.
        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.
        return image, matrix, step
Ejemplo n.º 13
0
def process_image(image):
    image = image.convert('RGB')
    image = image.filter(ImageFilter.SHARPEN)
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
    return pytesseract.image_to_string(image)


script_dir = os.path.dirname(__file__)  #<-- absolute dir the script is in
rel_path = "images/chotabheem.png"
abs_file_path = os.path.join(script_dir, rel_path)

img = Image.open(abs_file_path)

#img=process_image(img)
sharpener = ImageEnhance.Brightness(img.convert('RGB'))
#img=img.convert('RGB')

img = img.convert('L')

filtered_img = img.filter(ImageFilter.DETAIL)
print(filtered_img)
filtered_img.save("DETAIL.png", 'png')  #png support imagefilter
''' ImageFilter

    BLUR
    CONTOUR
    DETAIL
    EDGE_ENHANCE
    EDGE_ENHANCE_MORE
    EMBOSS
Ejemplo n.º 14
0
def main():
    image = Image.open("images/image.jpg")

    # crear imagen en blanco
    img = Image.new('RGBA', (800, 400), "blue")
    img.save('images/blanco.png')

    # Invertir colores.
    new_image = ImageChops.invert(image)
    new_image.save("images/image_1.jpg")

    # Escala de grises.
    new_image = ImageOps.grayscale(image)
    new_image.save("images/image_2.jpg")

    # Resaltar luces.
    new_image = ImageEnhance.Brightness(image).enhance(2)
    new_image.save("images/image_3.jpg")

    # Contraste.
    new_image = ImageEnhance.Contrast(image).enhance(4)
    new_image.save("images/image_4.jpg")

    # Espejo.
    new_image = ImageOps.mirror(image)
    new_image.save("images/image_5.jpg")

    # Cambiar tamaño.
    new_image = image.resize((320, 240))
    new_image.save("images/image_6.jpg")

    # Diminuir nitidez.
    new_image = ImageEnhance.Sharpness(image).enhance(-4)
    new_image.save("images/image_7.jpg")

    # split la imagen en bandas individuales
    source = image.split()

    R, G, B = 0, 1, 2

    # seleccionamos la region donde el rojo es menos a 100
    mask = source[R].point(lambda i: i < 100 and 255)

    # procesamos la banda verde
    out = source[G].point(lambda i: i * 0.7)

    # pegamos el procesado de la banda de vuelta, pero solo en la zona donde el rojo es menor a < 100
    source[G].paste(out, None, mask)

    # construimos la nueva imagen
    new_image = Image.merge(image.mode, source)
    new_image.save("images/image_8.jpg")

    # invertimos algunos colores manualmente
    r, g, b = image.split()
    new_image = Image.merge("RGB", (b, g, r))
    new_image.save("images/image_9.jpg")

    img = Image.open("images/image.jpg")
    draw = ImageDraw.Draw(img)
    #font = ImageFont.truetype("/ruta/LiberationSerif-Bold.ttf", 36)
    draw.text((200, 200), "Titulillo", (0, 2, 27))
    img.save('images/image_11.jpg')
Ejemplo n.º 15
0
def get_contrast_img(factor, base_img, res_img):
    im = Image.open(base_img)
    enhancer = ImageEnhance.Contrast(im)
    enhanced_im = enhancer.enhance(1.0 + factor)
    enhanced_im.save(res_img)
Ejemplo n.º 16
0
def upload_post():
    if not session.get('user_id'):
        return redirect(url_for('home_page'))

    comment = request.form['comment']
    location = request.form['location']
    upload_file = request.files['image']
    filters = request.form['filters']
    contrast = request.form['contrast']
    brightness = request.form['brightness']
    sharpness = request.form['sharpness']
    blur = request.form['blur']
    unsharpmask = request.form['unsharpmask']
    session_user_id = session['user_id']
    if upload_file:
        upload_file.save(os.path.join('static/uploads', upload_file.filename))
    else:
        return render_template('message.html',
                               message="Please select an image..")

    img = Image.open(os.path.join('static/uploads', upload_file.filename))

    needToSave = 0
    if blur != "0":
        img = img.filter(ImageFilter.GaussianBlur(float(blur)))
        needToSave = 1

    if unsharpmask != "0":
        img = img.filter(ImageFilter.UnsharpMask(float(unsharpmask)))
        needToSave = 1

    if sharpness != "0":
        enhancer = ImageEnhance.Sharpness(img)
        img = enhancer.enhance(float(sharpness))
        needToSave = 1

    if contrast != "0":
        enhancer = ImageEnhance.Contrast(img)
        img = enhancer.enhance(float(contrast))
        needToSave = 1

    if brightness != "0":
        enhancer = ImageEnhance.Brightness(img)
        img = enhancer.enhance(float(brightness))
        needToSave = 1

    if needToSave == 1:
        img.save(os.path.join('static/uploads', upload_file.filename))

    print(filters)
    gmaps = googlemaps.Client(key='AIzaSyDurbt3tU9F8lDMqyHAnXVjCPphapNu0FM')
    with psycopg2.connect(current_app.config['dsn']) as conn:
        crs = conn.cursor()

        crs.execute(
            "insert into images (user_id, path, time, text) values (%s,%s, now(), %s) RETURNING image_id",
            (session_user_id, upload_file.filename, comment))
        image_id = crs.fetchone()[0]  #Get image id
        #filter part
        if filters == "0":
            crs.execute(
                'insert into filter (name, user_id, contrast, Brightness, Sharpness, Blur, UnsharpMask) values (%s, %s, %s, %s, %s, %s, %s) RETURNING id',
                ("Saved Settings", session_user_id, contrast, brightness,
                 sharpness, blur, unsharpmask))
            filter_id = crs.fetchone()[0]
            crs.execute(
                'insert into image_filters (image_id, filter_id) values (%s, %s)',
                (image_id, filter_id))
            conn.commit()
        else:
            crs.execute(
                'update filter set contrast = %s, brightness = %s, sharpness = %s, blur = %s, unsharpmask = %s where id = %s and user_id = %s',
                (contrast, brightness, sharpness, blur, unsharpmask, filters,
                 session_user_id))
            filter_id = filters
            crs.execute(
                'insert into image_filters (image_id, filter_id) values (%s, %s)',
                (image_id, filter_id))
            conn.commit()
        if location:
            locs = location.split(',')
            order = 0
            #location check
            for loc in locs:
                #print(loc)
                crs.execute("select * from locations where name = %s", (loc, ))
                loc_data = crs.fetchone()
                loc_id = 0
                #get location id with insert or select
                if loc_data:
                    crs.execute(
                        'update locations set rating = rating + 1 where Id=%s',
                        ([loc_data[0]]))
                    loc_id = loc_data[0]
                else:
                    gcode = gmaps.geocode(loc)
                    formatted = gcode[0]['formatted_address']
                    location = gcode[0]['geometry']['location']
                    lng = location['lng']
                    lat = location['lat']
                    crs.execute(
                        'insert into locations (name, latitude, longitude, formatted_address, rating) values (%s, %s, %s, %s, %s) RETURNING Id',
                        (loc, lat, lng, formatted, 1))
                    loc_id = crs.fetchone()[0]  #Get last insertion id

                #add it to image_locations relation table
                crs.execute(
                    'insert into image_locations (image_id, location_id, order_val) values (%s, %s, %s)',
                    (image_id, loc_id, order))
                order = order + 1

        #notification insertion will use the logged user's information after the respective functionality is added - Halit
        crs.execute("select photo_path, username from users where Id !=%s",
                    (session['user_id'], ))
        data = crs.fetchone()
        crs.execute(
            "insert into notifications(user_id, notifier_id, notifier_name, icon, details, read_status, follow_status) values (%s, %s, %s, %s, %s, %s, %s)",
            (session['user_id'], session['user_id'], data[1], data[0], comment,
             'FALSE', 'TRUE'))
        data = conn.commit()

    return render_template('message.html', message="Uploaded..")
Ejemplo n.º 17
0
def random_contrast(img):
    prob = np.random.uniform(0, 1)
    if prob < cfg.contrast_prob:
        delta = np.random.uniform(-cfg.contrast_delta, cfg.contrast_delta) + 1
        img = ImageEnhance.Contrast(img).enhance(delta)
    return img
Ejemplo n.º 18
0
#!/usr/bin/env python3

import sys
import pathlib
from PIL import Image
from PIL import ImageEnhance

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('Usage:')
        print('aug INPUT_FILE OUTPUT_PATH')
        exit(1)

    _, input_path_str, output_path = sys.argv
    input_path = pathlib.Path(input_path_str)

    with open(input_path, 'rb') as ifp:
        base = Image.open(ifp)
        imgs = [base, base.transpose(method=Image.FLIP_LEFT_RIGHT)]

        lr = 0
        for img in imgs:
            for brightness in [0.5, 0.6, 0.7, 0.8, 0.9]:
                opath = '{}/{}.{}.{}.png'.format(output_path, input_path.stem,
                                                 lr, brightness)
                ImageEnhance.Brightness(img).enhance(brightness).save(opath)
            lr += 1
Ejemplo n.º 19
0
from PIL import Image
from PIL import ImageEnhance
#from pytesser import *
import pytesseract
#from pytesseract import pytesser
from pytesseract import image_to_string

im = Image.open("5.png")
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe'
nx, ny = im.size
im2 = im.resize((int(nx * 5), int(ny * 5)), Image.BICUBIC)
im2.save("temp2.png")
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")

imgx = Image.open('temp2.png')
imgx = imgx.convert("RGBA")
pix = imgx.load()
for y in range(imgx.size[1]):
    for x in range(imgx.size[0]):
        if pix[x, y] != (0, 0, 0, 255):
            pix[x, y] = (255, 255, 255, 255)
imgx.save("bw.gif", "GIF")
original = Image.open('bw.gif')
bg = original.resize((116, 56), Image.NEAREST)
ext = ".tif"
bg.save("input-NEAREST" + ext)
image = Image.open('input-NEAREST.tif')
print(image_to_string(image))
"""
from PIL import Image
Ejemplo n.º 20
0
def contrast(pil_img, level):
    level = float_parameter(sample_level(level), 1.8) + 0.1
    return ImageEnhance.Contrast(pil_img).enhance(level)
Ejemplo n.º 21
0
    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),
            "shearY":
            lambda img, magnitude: img.transform(img.size, Image.AFFINE, (
                1, 0, 0, magnitude * random.choice([-1, 1]), 1, 0), Image.
                                                 BICUBIC),
            "translateX":
            lambda img, magnitude: img.transform(img.size, Image.AFFINE, (
                1, 0, magnitude * img.size[0] * random.choice([-1, 1]
                                                              ), 0, 1, 0)),
            "translateY":
            lambda img, magnitude: img.transform(img.size, Image.AFFINE, (
                1, 0, 0, 0, 1, magnitude * img.size[1] * random.choice([-1, 1]
                                                                       ))),
            "rotate":
            lambda img, magnitude: rotate_with_fill(img, magnitude),
            # "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]
Ejemplo n.º 22
0
def sharpness(pil_img, level):
    level = float_parameter(sample_level(level), 1.8) + 0.1
    return ImageEnhance.Sharpness(pil_img).enhance(level)
Ejemplo n.º 23
0
def enhance(image, scale=1.3):
    enhancer = ImageEnhance.Brightness(image)
    return enhancer.enhance(scale)
Ejemplo n.º 24
0
def apply_brightness_shift(x, brightness):
    x = array_to_img(x)
    x = ImageEnhance.Brightness(x).enhance(brightness)
    x = img_to_array(x)
    return x
Ejemplo n.º 25
0
from PIL import Image, ImageEnhance

image = Image.open(':\\Users\\omar\\Desktop\\Site\\Images\\obama.png')
scale_value = scale1.get()
contrast = ImageEnhance.Contrast(image)
contrast_applied = contrast.enhance(scale_value)
image.show()
Ejemplo n.º 26
0
def apply_contrast_shift(x, contrast):
    x = array_to_img(x)
    x = ImageEnhance.Contrast(x).enhance(contrast)
    x = img_to_array(x)
    return x
Ejemplo n.º 27
0
def contrast(im, k=3):
    enhancer = ImageEnhance.Contrast(im)
    return enhancer.enhance(k)
Ejemplo n.º 28
0
def apply_sharpness_shift(x, sharpness):
    x = array_to_img(x)
    x = ImageEnhance.Sharpness(x).enhance(sharpness)
    x = img_to_array(x)
    return x
Ejemplo n.º 29
0
def brightness(im, k=3):
    enhancer = ImageEnhance.Brightness(im)
    return enhancer.enhance(k)
Ejemplo n.º 30
0
def image_augment(filename,angle=None,luminance=None,Contrast=None):
    #img = Image.open(filename)
    img = cv2.imread(filename)
    name = filename.split('_')
    path = os.getcwd()
    currentdir = path.split('\\')    
    paraent_path = os.path.dirname(path)    
    if angle is not None:
        ropath = os.path.join(paraent_path,currentdir[-1]+'_rotate')
        rodirsuccess = mkdir(ropath)
        for a in angle:
#            img = img.rotate(a)
            rows,cols,channels = img.shape
            M = cv2.getRotationMatrix2D((cols/2,rows/2),a,1)
            dst = cv2.warpAffine(img,M,(cols,rows))
            rotation_name = name[0]+'_ro'+str(a)
            for n in name[1:]:
                rotation_name+=('_'+n)         
                save_path = os.path.join(ropath,rotation_name)
            try:
#                img.save(save_path)
                cv2.imwrite(save_path,dst)
            except IOError:
                print("cannot rotation")
    else:
        #print("Don't do any rotation")
        pass
    
    if luminance is not None:
        lupath = os.path.join(paraent_path,currentdir[-1]+'_luminance')
        ludirsuccess = mkdir(lupath)
        for l in luminance:
            img = ImageEnhance.Brightness(img).enhance(l)
            luminance_name = name[0]+'_lu'+str(l)
            for n in name[1:]:
                luminance_name+=('_'+n)         
                save_path = os.path.join(lupath,luminance_name)
            try:
                img.save(save_path)
            except IOError:
                print("cannot enhance luminance")
    else:
        #print("Don't do any lumiance enhancement")
        pass
        
    if Contrast is not None:
        copath = os.path.join(paraent_path,currentdir[-1]+'_contrast')
        codirsuccess = mkdir(copath)
        for C in Contrast:
            img = ImageEnhance.Contrast(img).enhance(C)
            contrast_name = name[0]+'_co'+str(C)
            for n in name[1:]:
                contrast_name+=('_'+n)         
                save_path = os.path.join(copath,contrast_name)
            try:
                img.save(save_path)
            except IOError:
                print("cannot enhance contrast")
    else:
        #print("Don't do any contrast enhancement")
        pass