Exemplo n.º 1
0
 def get_pic(self):
     time.sleep(2)
     target = browser.find_element_by_class_name("yidun_bg-img")
     template = browser.find_element_by_class_name("yidun_jigsaw")
     target_link = target.get_attribute('src')
     template_link = template.get_attribute('src')
     target_img = Image.open(BytesIO(requests.get(target_link).content))
     template_img = Image.open(BytesIO(requests.get(template_link).content))
     target_img.save('target.jpg')
     template_img.save('template.png')
     size_orign = target.size
     local_img = Image.open('target.jpg')
     size_loc = local_img.size
     self.zoom = 320 / int(size_loc[0])
Exemplo n.º 2
0
def frame2base64(frame):
    img = Image.fromarray(frame)  #将每一帧转为Image
    output_buffer = BytesIO()  #创建一个BytesIO
    img.save(output_buffer, format='JPEG')  #写入output_buffer
    byte_data = output_buffer.getvalue()  #在内存中读取
    # base64_data = base64.b64encode(byte_data) #转为BASE64
    return byte_data  #转码成功 返回base64编码
    def show(self) :
        #open the image file from the path given
        try : image = Image.open(self.image_path)
        except IOError : 
            print "IOError"
            return

        image.show()
Exemplo n.º 4
0
 def tesseractCharacter(self):
     self.plate_characters = sorted(self.plate_characters,
                                    key=lambda x: x[0])
     # sort contours left to right
     for character in self.plate_characters[:8]:  # only first 8 contours
         char_image = Image.fromarray(character[1])
         char = tes.image_to_string(char_image, config='-psm 10')
         self.plate_number += char.upper()
     return True
    def show(self):
        #open the image file from the path given
        try:
            image = Image.open(self.image_path)
        except IOError:
            print "IOError"
            return

        image.show()
Exemplo n.º 6
0
 def metadata_get_exif(self):
     ret = {}
     from PIL import Image
     from PIL.ExifTags import TAGS
     i = Image.open(self)
     info = i._getexif()
     for tag, value in info.items():
         decoded = TAGS.get(tag, tag)
         ret[decoded] = value
     return ret
Exemplo n.º 7
0
def get_png_grayvalue(filename):
    try: 
        from pillow import Image
    except:
        import Image
    I = Image.open(filename)
    D = numpy.array(I.getdata())
    if len(D.shape) > 1:
        D = numpy.array(I.getdata())[:,0]
    D = D.reshape((I.size[1],I.size[0]))
    return D
Exemplo n.º 8
0
def obscure(rects):
    """ Takes an array of rects to obscure from the screenshot. """
    image = Image.open('/tmp/.i3lock.png')

    for rect in rects:
        area = (rect.x, rect.y, rect.x + rect.width, rect.y + rect.height)

        cropped = image.crop(area)
        cropped = obscure_image(cropped)
        image.paste(cropped, area)

    image.save('/tmp/.i3lock.png')
Exemplo n.º 9
0
 def runTest(self):
     symbology = self.conf.symbology
     img_prefix = join(IMG_ROOT, symbology)
     for args in self.conf.cases:
         img_filename, codestring = args[:2]
         options = args[2] if len(args)>2 else {}
         render_options = dict((args[3] if len(args)>3 else {}), scale=2.0)
         generated = barcode(symbology, codestring, options, **render_options).convert('L')
         loaded = Image.open(join(img_prefix, img_filename)).convert('L')
         diff = None
         try:
             # image size comparison
             self.assertEqual(generated.size, loaded.size)
             # pixel-wize comparison
             diff = ImageChops.difference(generated, loaded)
             diff_bbox = diff.getbbox()
             self.assertIsNone(diff_bbox)
         except AssertionError as exc:
             # generate and show diagnostics image
             if diff:
                 # if diff exists, generate 3-row diagnostics image
                 lw, lh = loaded.size
                 gw, gh = generated.size
                 diag = Image.new('L', (max(lw, gw), (lh+gh+max(lh, gh))))
                 diag.paste(loaded, (0, 0, lw, lh))
                 diag.paste(generated, (0, lh, gw, lh+gh))
                 diag.paste(diff, (0, lh+gh, max(lw, gw), (lh+gh+max(lh, gh))))
             else:
                 # else, just write generated image
                 diag = generated
             sio_img = StringIO()
             diag.convert('L').save(sio_img, 'PNG')
             # reopen sio_img
             sio_img = StringIO(sio_img.getvalue())
             sio_uu = StringIO()
             uuencode(sio_img, sio_uu, name='diag_%s' %img_filename)
             raise AssertionError(
                 'Image difference detected (%s)\n'
                 'uu of generated image:\n----\n%s----\n'
                 %(exc.args, sio_uu.getvalue()))
Exemplo n.º 10
0
def draw_image_rect(image_path, rects):
    im = np.array(Image.open(image_path), dtype=np.uint8)
    fig, ax = plt.subplots(1)
    ax.imshow(im)
    for rect in rects:
        draw_rect = patches.Rectangle((rect[1], rect[0]),
                                      rect[2],
                                      rect[3],
                                      linewidth=3,
                                      edgecolor='b',
                                      facecolor='none')
        ax.add_patch(draw_rect)
    plt.show()
Exemplo n.º 11
0
def makeCardImage(name, rules):
    img = Image.new('RGB', (500, 726), color='white')

    rulesf = textwrap.fill(rules, 40)  #wrap that text bb

    d = ImageDraw.Draw(img)
    d.text((20, 20), name, fill=(0, 0, 0), font=titleF)
    d.text((20, 500), rulesf, fill=(0, 0, 0), font=rulesF)

    file = filize(name, 'png')
    img.save(file)

    return file
Exemplo n.º 12
0
def obscure(rects):
  """ Takes an array of rects to obscure from the screenshot. """
  image = Image.open('/tmp/.i3lock.png')

  for rect in rects:
    area = (
      rect.x, rect.y,
      rect.x + rect.width,
      rect.y + rect.height
    )

    cropped = image.crop(area)
    cropped = obscure_image(cropped)
    image.paste(cropped, area)

  image.save('/tmp/.i3lock.png')
Exemplo n.º 13
0
def get_png_mask(filename):
    try: 
        from pillow import Image
    except:
        try:
            import Image
        except:
            import image as Image
    I = Image.open(filename)
    D = numpy.array(I.getdata())
    if len(D.shape) > 1:
        D = numpy.array(I.getdata())[:,0]
    D = D.reshape((I.size[1],I.size[0]))
    D = D[:,:]/255.
    D = D.round()
    D = numpy.int16(D)
    return D
Exemplo n.º 14
0
    def __call__(self, jarvis, s):

        if not s:
            jarvis.say("please enter file path after calling the plugin")
        elif not "png" in s:
            jarvis.say("Your file must be a .png file")
        else:
            #We have to add the '.' back beacause the Jarvis API removes it
            s = s.replace('png', '.' + 'png')

            source_path = s
            dest_path = s.replace('.png', '') + '.pdf'
            image = Image.open(source_path)

            pdf_bytes = img2pdf.convert(source_path.filename)
            file = open(dest_path, "wb")
            file.write(pdf_bytes)
            image.close()
            file.close()
            jarvis.say("file successfully converted")
Exemplo n.º 15
0
#!C:\Anaconda3\Python
#coding=utf-8


from pillow import Image

print("=============== PIL ==================")

im = Image.open('00_10_ExternalClasses.png')
w, h = im.size
print('Original image size: %sx%s' % (w, h))

im.thumbnail((w//2, h//2))
print('Resize image to: %sx%s' % (w//2, h//2))
im.save('00_10_ExternalClasses_0.jpg', 'jpeg')
#! /usr/bin/env python3

from pillow import Image  #图像处理模块
import numpy as np

a = np.asarray(Image.open("这里是原图片的路径").convert('L')).astype(
    'float')  #将图像以灰度图的方式打开并将数据转为float存入np中

depth = 10.  # (0-100)
grad = np.gradient(a)  #取图像灰度的梯度值
grad_x, grad_y = grad  #分别取横纵图像梯度值
grad_x = grad_x * depth / 100.
grad_y = grad_y * depth / 100.
A = np.sqrt(grad_x**2 + grad_y**2 + 1.)
uni_x = grad_x / A
uni_y = grad_y / A
uni_z = 1. / A
#建立一个位于图像斜上方的虚拟光源
vec_el = np.pi / 2.2  # 光源的俯视角度,弧度值
vec_az = np.pi / 4.  # 光源的方位角度,弧度值
dx = np.cos(vec_el) * np.cos(vec_az)  #光源对x 轴的影响
dy = np.cos(vec_el) * np.sin(vec_az)  #光源对y 轴的影响
dz = np.sin(vec_el)  #光源对z 轴的影响
#计算各点新的像素值
b = 255 * (dx * uni_x + dy * uni_y + dz * uni_z)  #光源归一化
b = b.clip(0, 255)  #clip函数将区间外的数字剪除到区间边缘

im = Image.fromarray(b.astype('uint8'))  #重构图像
im.save("这里是输出图片的路径")
Exemplo n.º 17
0
    def create(self, imlist, namelist, desclist=None):
        """ Main method to create the actual strip
        
        :param imlist: PIL images, ej: [[img1, img2],[img3, img4]]
        :type imlist: list of lists
        :param namelist: Names for the images. Must match imlist size
        :type namelist: list of lists
        :param desclist: Descriptions for the images. Must match imlist size
        :type desclist: list of lists
        :return:
        :rtype:
        """

        # SANITY CHECK
        err1 = "dimension of imlist must match dimension of namelist"
        err2 = "dimension of nested lists must be equal"

        if len(imlist) != len(namelist):
            raise ValueError(err1)
        elif [len(l) for l in imlist] != [len(l) for l in namelist]:
            raise ValueError(err2)

        if desclist is not None:
            if len(desclist) != len(imlist):
                raise ValueError(err1)
            elif [len(l) for l in imlist] != [len(l) for l in desclist]:
                raise ValueError(err2)

        def line_height(text, font):
            """ Calculate height for a multiline text
            
            :param text: multiline text
            :type text: str
            :param font: utilized font
            :type font: ImageFont
            :return: text height
            :rtype: float
            """
            lista = text.split("\n")
            alt = 0
            for linea in lista:
                alt += font.getsize(linea)[1]
            return alt + self.y_space

        # FUENTES
        font = ImageFont.truetype(self.font, self.body_size)
        fontit = ImageFont.truetype(self.font, self.title_size)
        font_desc = ImageFont.truetype(self.font, self.title_size - 4)

        # TITULO
        title = self.name
        title_height = line_height(title, fontit)
        
        # DIMENSIONES DESCRIPCION
        description = self.description.replace("_", "\n")
        desc_height = line_height(description, font_desc)
        desc_width = font_desc.getsize(description)[0]

        # ALTURA NOMBRES
        if desclist:
            all_names = [n.replace("_", "\n") for n in self.unpack(desclist)]
        else:
            all_names = [n.replace("_", "\n") for n in self.unpack(namelist)]

        all_height = [line_height(t, font) for t in all_names]
        name_height = max(*all_height) #+ 2
        # print alturatodos, alturanombres

        # CALCULO EL ANCHO DE LA PLANTILLA
        imgs_width = [[ii.size[0] + self.x_space for ii in i] for i in imlist]
        imgs_width_sum = [sum(i) for i in imgs_width]

        # CALCULO EL MAXIMO ANCHO DE LA LISTA DE ANCHOS
        max_width = max(imgs_width_sum)
        strip_width = int(max_width)

        # CALCULO EL ALTO MAX

        # POR AHORA LO CALCULA CON EL ALTO DE LA 1ER COLUMNA
        # PERO SE PODRIA CALCULAR CUAL ES LA IMG MAS ALTA Y CUAL
        # ES EL TITULO MAS ALTO, Y COMBINAR AMBOS...

        # Tener en cuenta que listaimgs es una lista de listas [[i1,i2], [i3,i4]]

        # print "calculando general_height de la plantilla..."

        imgs_height = [[ii.size[1] for ii in i] for i in imlist]
        max_imgs_height = [max(*i) + name_height + self.y_space for i in imgs_height]
        max_height = sum(max_imgs_height)

        strip_height = int(sum((title_height, desc_height, max_height,
                                    self.y_space * 3)))

        strip = ImPIL.new("RGB", (strip_width, strip_height),
                              self.background_color)

        draw = ImageDraw.Draw(strip)

        # DIBUJA LOS ELEMENTOS DENTRO DE LA PLANTILLA

        # COORD INICIALES
        x = 0
        y = 0

        # DIBUJA EL TITULO
        draw.text((x, y), title, font=fontit, fill=self.title_color)

        # DIBUJA LA DESCRIPCION
        y += title_height + self.y_space # aumento y
        # print "y de la descripcion:", y
        draw.text((x, y), description, font=font_desc, fill=self.title_color)

        # DIBUJA LAS FILAS

        # logging.debug(("altura de la descripcion (calculada):", desc_height))
        # logging.debug(("altura de la desc", font_desc.getsize(description)[1]))
        y += desc_height + self.y_space # aumento y

        # DIBUJA LAS FILAS Y COLUMNAS

        if desclist:
            namelist = desclist

        for i, n, alto in zip(imlist, namelist, max_imgs_height):
            # RESETEO LA POSICION HORIZONTAL
            xn = x # hago esto porque en cada iteracion aumento solo xn y desp vuelvo a x
            for image, name in zip(i, n):
                # LA COLUMNA ES: (imagen, name, anchocolumna)
                # print image, name

                ancho_i, alto_i = image.size

                # DIBUJO imagen
                strip.paste(image, (xn, y))

                # aumento y para pegar el texto
                _y = y + alto_i + self.y_space

                # DIBUJO name
                draw.text((xn, _y),
                          name.replace("_", "\n"),
                          font=font,
                          fill=self.body_color)

                # AUMENTO y
                xn += ancho_i + self.x_space

            # AUMENTO x
            y += alto

        strip.save(self.name + "." + self.ext)
        strip.show()

        return strip
Exemplo n.º 18
0
    def from_list(self, imlist, namelist, viz_bands, min, max, region,
                  folder, check=True, desclist=None, **kwargs):
        """ Download every image and create the strip

        :param imlist: Satellite Images (not PIL!!!!!!)
        :type imlist: list of ee.Image
        :param namelist: Names for the images. Must match imlist
        :type namelist: list of str
        :param desclist: list of descriptions for every image. Optional
        :type desclist: list of str
        :param viz_bands: Visualization bands. ej: ["NIR","SWIR","RED"]
        :type viz_bands: list of str
        :param min: min value for visualization
        :type min: int
        :param max: max value for visualization
        :type max: int
        :param region: coordinate list. Optional
        :type region: list
        :param folder: folder to downlaod files. Do not use '/' at the end
        :type folder: str
        :param check: Check if file exists, and if it does, omits the downlaod
        :type check: bool
        :param draw_polygons: Polygons to draw over the image. Must be a list of list of
            coordinates. Optional
        :type draw_polygons: list of list
        :param draw_lines: Lines to draw over the image
        :type draw_lines: list of list
        :param draw_points: Points to draw over the image
        :type draw_points: list of list
        :param general_width: Images width
        :type general_width: int

        :return: A file with the name passed to StripImage() in the folder
            passed to the method. Opens the generated file
        """

        if isinstance(imlist, ee.List):
            imlist = listEE2list(imlist, 'Image')

        region = ee.Geometry.Polygon(region).bounds().getInfo()["coordinates"]

        # TODO: modificar este metodo para que se pueda pasar listas de listas
        general_width = kwargs.get("general_width", 500)

        draw_polygons = kwargs.get("draw_polygons", None)
        draw_lines = kwargs.get("draw_lines", None)
        draw_points = kwargs.get("draw_points", None)

        # desclist = kwargs.get("desclist", None)

        list_of_lists = []

        # logging.debug(("verificar archivo?", check))

        # for i in range(0, len(imlist)):
        for img_list, nom_list in zip(imlist, namelist):
            pil_img_list = []
            for image, name in zip(img_list, nom_list):
                # name = namelist[i]
                # exist = os.path.exists(folder+"/"+name)
                # path = "{0}/{1}.{2}".format(folder, name, self.ext)

                # CHECK CARPETA
                abscarp = os.path.abspath(folder)
                if not os.path.exists(abscarp):
                    os.mkdir(abscarp)

                path = "{}/{}".format(folder, name)
                fullpath = os.path.abspath(path)+"."+self.ext
                exist = os.path.isfile(fullpath)

                logging.debug(("existe {}?".format(fullpath), exist))

                if check and exist:
                    im = ImPIL.open(fullpath)
                else:
                    img = ee.Image(image)
                    urlviz = img.visualize(bands=viz_bands, min=min, max=max,
                                           forceRgbOutput=True)

                    url = urlviz.getThumbURL({"region": region,
                                              "format": self.ext,
                                              "dimensions": general_width})

                    # archivo = funciones.downloadFile3(url, folder+"/"+name, self.ext)
                    file = batch.downloadFile(url, path, self.ext)

                    im = ImPIL.open(file.name)
                    # listaimPIL.append(im)

                dr = ImageDraw.Draw(im)

                general_width, general_height = im.size
                # print "general_width:", general_width, "general_height:", general_height

                # nivel de 'anidado' (nested)
                def nested_level(l):
                    n = 0
                    while type(l[0]) is list:
                        n += 1
                        l = l[0]
                    return n

                region = region[0] if nested_level(region) == 2 else region
                region = region[:-1] if len(region) == 5 else region

                p0 = region[0]
                p1 = region[1]
                p3 = region[3]
                distX = abs(p0[0]-p1[0])
                distY = abs(p0[1]-p3[1])

                # FACTORES DE ESCALADO
                width_ratio = float(general_width)/float(distX)
                height_ratio = float(general_height)/float(distY)

                if draw_polygons:
                    for pol in draw_polygons:
                        pol = [tuple(p) for p in pol]

                        newpol = [(abs(x-p0[0])*width_ratio, abs(y-p0[1])*height_ratio) for x, y in pol]

                        # logging.debug("nuevas coords {}".format(newpol))

                        #print "\n\n", pol, "\n\n"
                        dr.polygon(newpol, outline="red")

                pil_img_list.append(im)
            list_of_lists.append(pil_img_list)

        if desclist:
            return self.create(list_of_lists, namelist, desclist)
        else:
            return self.create(list_of_lists, namelist)
Exemplo n.º 19
0
import pandas as pd
from pillow import Image

train_csv_path = "./msd-train/__DressType_msd_train-prod.csv"

train_csv = pd.read_csv(train_csv_path)

urls = train_csv["image_urls"] # list of all the image urls in the training CSV
alt_urls = train_csv[""

for img_path in image_paths:
    with Image.open(img_path) as img:
        width, height = img.size
    
from wand.image import Image
from pillow import Image as PI
import pyocr
import pyocr.builders
import io

tool = pyocr.get_available_tools()[0]
lang = tool.get_available_languages()[1]
req_image = []
final_text = []
image_pdf = Image(filename="C:/Users/jai/Desktop/Receipt - Generic.pdf", resolution=300)
image_jpeg = image_pdf.convert('jpeg')
for img in image_jpeg.sequence:
    img_page = Image(image=img)
    req_image.append(img_page.make_blob('jpeg'))
for img in req_image:
    txt = tool.image_to_string(
        PI.open(io.BytesIO(img)),
        lang=lang,
        builder=pyocr.builders.TextBuilder()
    )
    final_text.append(txt)
print (final_text)
Exemplo n.º 21
0
def tiff_to_nparray(f):
    im = Image.open(f)
    imarray = np.array(im)
    return imarray
Exemplo n.º 22
0
    x0 = x * mat[i][0] + y * mat[i][1] + mat[i][4] 
    y  = x * mat[i][2] + y * mat[i][3] + mat[i][5] 
    x = x0 
    #
    if x < xa:
        xa = x
    if x > xb:
        xb = x
    if y < ya:
        ya = y
    if y > yb:
        yb = y

# drawing
#imgy = round(imgy * (yb - ya) / (xb - xa)) # auto-re-adjust the aspect ratio 
image = Image.new("L", (imgx, imgy))

x=0.0
y=0.0 
for k in range(imgx * imgy):
    p=random.random()
    psum = 0.0
    for i in range(m):
        psum += mat[i][6]
        if p <= psum:
            break
    x0 = x * mat[i][0] + y * mat[i][1] + mat[i][4] 
    y  = x * mat[i][2] + y * mat[i][3] + mat[i][5] 
    x = x0 
    jx = int((x - xa) / (xb - xa) * (imgx - 1)) 
    jy = (imgy - 1) - int((y - ya) / (yb - ya) * (imgy - 1))
Exemplo n.º 23
0
import requests
from pillow import Image
from io import BytesIO
import csv

url = 'http://www.yswhosting.com/sandbox/don/images/padded/phi-delta-theta-tablecloth.jpg'
data = BytesIO(requests.get(url).content)
img = Image.open(data)
print 'a', img.size
output_file = "".join(
    ["../OutputData/GreekGear/", 'GreekGear.com-images-size.csv'])
print("output file is ", output_file)
final_csv_file = open(
    output_file,
    "wb")  # binary mode to not add extra line breaks between rows in windows
writer = csv.writer(final_csv_file)
writer.writerow([img.size, url])

# import urllib, cStringIO
# from PIL import Image

# # given an object called 'link'

# #SITE_URL = "http://www.targetsite.com"
# #URL = SITE_URL + link['src']
# # Here's a sample url that works for demo purposes
# URL = "http://www.yswhosting.com/sandbox/don/images/padded/phi-delta-theta-tablecloth.jpg"
# file = cStringIO.StringIO(urllib.urlopen(URL).read())
# im=Image.open(file)
# print(im.size)
#width, height = im.size
Exemplo n.º 24
0
Date()
now = datetime.now()

print("Проверено : ", datetime.strftime(datetime.now(), "%Y.%m.%d %H:%M:%S"))

while True:
    var = int(
        input("Введите вариант развития события(1 2 3 (0 для выхода))" + "\n"))

    if var == 1:
        for i, ii in enumerate(X1):
            if X1[i] > max:
                max = X1[i]
                iter = i
        img = Image.open('ptkRel1.jpg')

        if max >= 0.00 and max <= 0.35:
            mixer.music.load('looking.mp3')

        if max >= 0.36 and max <= 0.60:
            sost = V[1]
            mixer.music.load('BPLA.mp3')

        if max >= 0.61 and max <= 1.00:
            sost = V[2]
            mixer.music.load('Fireman.mp3')
        print("Состояние: ", sost)
        img.show()
        mixer.music.play()
    max = -1
Exemplo n.º 25
0
def rgb_conv(i):
    color = 255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5))
    return tuple(color.astype(int))


# function defining a mandelbrot
def mandelbrot(x, y):
    c0 = complex(x, y)
    c = 0
    for i in range(1, 1000):
        if abs(c) > 2:
            return rgb_conv(i)
        c = c * c + c0
    return (0, 0, 0)


# creating the new image in RGB mode
img = Image.new('RGB', (WIDTH, int(WIDTH / 2)))
pixels = img.load()

for x in range(img.size[0]):

    # displaying the progress as percentage
    print("%.2f %%" % (x / WIDTH * 100.0))
    for y in range(img.size[1]):
        pixels[x, y] = mandelbrot((x - (0.75 * WIDTH)) / (WIDTH / 4),
                                  (y - (WIDTH / 4)) / (WIDTH / 4))

    # to display the created fractal after
# completing the given number of iterations
img.show()
Exemplo n.º 26
0
__author__ = 'webon'

from pillow import Image
import glob, os

size = 200, 200

for infile in glob.glob('C:/Users/webon/Desktop/loan-officer-images.2902jpg'):
    file, ext = os.path.splitext(infile)
    im = Image.open(infile)
    im.thumbnail(size)
    im.save(file + '.thumbnail', 'JPEG')
Exemplo n.º 27
0
# 图片格式转换, Jpg转Png

# 方法①
from pillow import Image

img = Image.open('test.jpg')
img.save('test1.png')

# 方法②
from cv2 import imread, imwrite

image = imread("test.jpg", 1)
imwrite("test2.png", image)
Exemplo n.º 28
0
'''import cv2
import numpy as np
import pyzbar.pyzbar as pyzbar

image = cv2.imread("bca.jpg")


decodedObjects = pyzbar.decode(image)
for obj in decodedObjects:
    print("obj", obj)
    print("Type:", obj.type)
    print("Data: ", obj.data, "\n")

cv2.imshow("Frame", image)
cv2.waitKey(0)
'''
from pillow import Image
from tesseract import image_to_string
print( image_to_string(Image.open('IMG_20200116_151537__01.jpg')) )
print( image_to_string(Image.open('IMG_20200116_151537__01.jpg'), lang='eng') )