Пример #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])
    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()
    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()
Пример #4
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
Пример #5
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
Пример #6
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')
Пример #7
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()
Пример #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')
Пример #9
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
Пример #10
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")
Пример #11
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()))
Пример #12
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("这里是输出图片的路径")
Пример #14
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)
Пример #15
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)
Пример #17
0
def tiff_to_nparray(f):
    im = Image.open(f)
    imarray = np.array(im)
    return imarray
Пример #18
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
Пример #19
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
Пример #20
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')
Пример #21
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)
Пример #22
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') )