当前位置: 首页>>代码示例>>Python>>正文


Python image.Image类代码示例

本文整理汇总了Python中wand.image.Image的典型用法代码示例。如果您正苦于以下问题:Python Image类的具体用法?Python Image怎么用?Python Image使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Image类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pdf2text

def pdf2text(pdf_filename):

    tool = pyocr.get_available_tools()[0]
    lang = tool.get_available_languages()[1]

    req_image = []
    final_text = []

    image_pdf = Image(filename=pdf_filename, 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)

    return final_text
开发者ID:jonesram,项目名称:manhattan-project-scratch,代码行数:26,代码来源:ocr_pdf.py

示例2: pdf2img

def pdf2img(pdf_path):
    print "Converting pdf section to image..."
    img = Image(filename=pdf_path)
    imgname=pdf_path[:pdf_path.rindex('.')]+ext
    print "Saving image: "+imgname[imgname.rindex('\\')+1:]
    img.save(filename=imgname)
    return imgname
开发者ID:wantsomechocolate,项目名称:PDF2EXCEL,代码行数:7,代码来源:initial_efforts.py

示例3: _create_image

    def _create_image(self, image_argument):
        image = None

        if isinstance(image_argument, Image):
            image = image_argument

        if isinstance(image_argument, (str, unicode)):
            image_file = urllib.urlopen(image_argument)
            image = Image(blob=image_file.read())

        elif isinstance(image_argument, dict):
            config = image_argument
            if 'raw_image' not in config:
                raise KeyError("Should have image in config")

            if not isinstance(config['raw_image'], Image):
                raise TypeError("config['raw_image'] should be Image")

            image = config['raw_image']
            transforms = config.get('transforms', [])

            for t in transforms:
                image.transform(**t)

        if image is None:
            raise ValueError("Generate Fail")

        return image
开发者ID:wooparadog,项目名称:wand_wielder,代码行数:28,代码来源:parameters.py

示例4: generate_square_img

	def generate_square_img(self, img_path, size_config, size_img, size_name, dest_path):
		#open_image
		img = Image(filename=img_path)
		#transform with resize scale config
		img.transform(resize=size_config)
		#try to crop, calculate width crop first
		target_size = size_img[1] #use one because its square
		width, height = img.size
		#print "width, height ", width, height
		crop_start, crop_end = [0, 0] #add new size params
		#calculate
		crop_start = (width - target_size) / 2
		crop_end = crop_start + target_size
		
		#print crop_start, crop_end, target_size, (crop_end - crop_start)
		'''
		exProcessor = ExifData()
		#rotate image if necessary
		if exProcessor.check_orientation(img) in [6, 7]:
			img.rotate(90)
			img.metadata['exif:Orientation'] = 1
		if exProcessor.check_orientation(img) in [6, 8]:
			img.rotate(-90)
			img.metadata['exif:Orientation'] = 1
		if exProcessor.check_orientation(img) in [3, 4]:
			img.rotate(180) 
			img.metadata['exif:Orientation'] = 1
		'''

		#do cropping
		with img[crop_start:crop_end, :] as square_image:
			#save 
			square_image.save(filename=''.join([dest_path, size_name, '.jpg']))
开发者ID:adzymaniac,项目名称:potongin,代码行数:33,代码来源:ImagickHelper.py

示例5: create_thumb

    def create_thumb(self, img_path, date, text):

        img = Image(filename=os.path.join(self.source_dir, img_path))
        img.resize(self.thumb_size, self.thumb_size)

        pixmap_on = QtGui.QPixmap()
        pixmap_on.loadFromData(img.make_blob())

        with Drawing() as draw:
            draw.stroke_color = Color('white')
            draw.stroke_width = 3
            draw.line((0, 0), (self.thumb_size, self.thumb_size))
            draw.line((0, self.thumb_size), (self.thumb_size , 0))
            draw(img)

        pixmap_off = QtGui.QPixmap()
        pixmap_off.loadFromData(img.make_blob())
        
        btn = IconButton(pixmap_on, pixmap_off, img_path, date, text)
        btn.clicked.connect(self.thumb_clicked)

        size = pixmap_on.size()
        w, h = size.toTuple()
        btn.setIconSize(size)
        btn.setFixedSize(w+20, h+20)

        self.scroll_vbox.addWidget(btn)
开发者ID:petfactory,项目名称:python,代码行数:27,代码来源:instagram_ui.py

示例6: pdf2ocr

def pdf2ocr(pdffile):
    """
    Optical Character Recognition on PDF files using Python
    see https://pythontips.com/2016/02/25/ocr-on-pdf-files-using-python/
    :param pdffile: pdffile to be OCR'd
    :return:
    """
    from wand.image import Image
    from PIL import Image as PI
    import pyocr
    import pyocr.builders
    import io

    tool = pyocr.get_available_tools()[0]
    lang = tool.get_available_languages()[0]  # [0] for english
    req_image = []
    final_text = []
    print "Reading {0}".format(pdffile)
    image_pdf = Image(filename=pdffile, resolution=300)
    image_jpeg = image_pdf.convert("jpeg")
    for img in image_jpeg.sequence:
        img_page = Image(image=img)
        print ("appending image")
        req_image.append(img_page.make_blob("jpeg"))
    print "Generating text"
    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)
    return final_text
开发者ID:mfacorcoran,项目名称:utils,代码行数:29,代码来源:pdf2txt.py

示例7: do_polaroid

def do_polaroid (image, filename=None, background="black", suffix=None):
  if suffix is None:
    suffix = PARAMS["IMG_FORMAT_SUFFIX"]
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
  tmp.close()
  
  print("Saving image into {}...".format(tmp.name))
  image.save(filename=tmp.name)
  print("Done")
  
  if not(PARAMS["WANT_NO_CAPTION"]) and filename:
    details = get_file_details(filename)
    caption = """-caption "%s" """ % details.replace("'", "\\'")
  else:
    caption = ""
    
  command = ("convert "
             "-bordercolor snow "+
             "-background %(bg)s "+
             "-gravity center %(caption)s "+
             "+polaroid %(name)s %(name)s") % {"bg" : background, "name":tmp.name, "caption":caption}
             
  ret = subprocess.call(command, shell=True)
  if ret != 0:
    raise Exception("Command failed: "+ command)
  
  img = Image(filename=tmp.name).clone()
  
  os.unlink(tmp.name)
  
  img.resize(width=image.width, height=image.height)

  return img
开发者ID:wazari972,项目名称:photowall,代码行数:33,代码来源:photowall.py

示例8: wand1

def wand1():
    """This is Python Wand example 1"""
    the_time = t.asctime()

    print "Importing image ", IFILE
    img_1 = Image(filename=IFILE)

    print "Cropping and resizing the image"
    img_1.crop(300, 0, width=300, height=282)
    img_1.resize(width=600, height=564)

    print "Creating a drawing and overlaying on it"
    draw = Drawing()

    draw.circle((100, 100), (120, 120))

    draw.rectangle(left=img_1.width-300, top=img_1.height-45, width=230,
               height=40, radius=5)

    draw.font_size = 17
    draw.fill_color = Color('white')
    draw.text_color = Color('white')
    draw.text(img_1.width-290, img_1.height-20, the_time)
    draw(img_1)

    print "Displaying, close the XTERM when done"
    display(img_1)
开发者ID:wadester,项目名称:wh_test_py,代码行数:27,代码来源:gr_wand1.py

示例9: create_thumb

def create_thumb(size, blob):
    '''Creates proportionally scaled thumbnail and save to destination. Returns thumbnaill location and source mimetype'''
    mimetype = None
    with Image(blob=blob) as source:
        image = Image(source.sequence[0]) if source.sequence else source
        
        mimetype = image.mimetype
        if mimetype == None:
            raise InvalidImageException('Invalid image mimetype!')
        
        w, h = image.size
        if w > size[0]:
            h = int(max(h * size[0] / w, 1))
            w = int(size[0])
        if h > size[1]:
            w = int(max(w * size[1] / h, 1))
            h = int(size[1])
        size = w, h

        if size == image.size:
            #image.save(filename=destination + '.' + extension)
            return image, mimetype
    
        image.sample(*size)
        #image.save(filename=destination + '.' + extension)

        return image, mimetype
开发者ID:interphx,项目名称:noxboard,代码行数:27,代码来源:util.py

示例10: convert

 def convert(self, PDFname):
   p = Image(file = PDFname, format = 'png')
   p = p.sequence[0]
   p = Image(p)
   p.resize(50, 50)
   #p.save(filename = "test.png") #This line is for demos
   return p
开发者ID:jenkinjk,项目名称:RHIT-Senior-Project-Open-Access-Publishing-System-Sean-Feeney,代码行数:7,代码来源:PDF_To_PNG_Converter.py

示例11: _pdf_thumbnail

def _pdf_thumbnail(filename):
    img = WandImage(filename=filename + '[0]')
    img.background_color = Color('white')
    tw, th = get_thumbnail_size(img.height, img.width, 50, 50)
    img.resize(tw, th)
    rawData = img.make_blob('jpeg')
    return base64.b64encode(rawData)
开发者ID:CaliopeProject,项目名称:CaliopeServer,代码行数:7,代码来源:thumbnails.py

示例12: new_blank_png

def new_blank_png(width, height, color=None):
    if color:
        new_img = Image(width=width, height=height, background=color)
    else:
        new_img = Image(width=width, height=height)

    return new_img.convert('png')
开发者ID:zastre,项目名称:sandboxattempt,代码行数:7,代码来源:cover.py

示例13: main

def main(argv):
  input_file_spec = ''
  output_file_path = ''
  if len(argv) != 3:
    print 'usage: proeprocess_images.py <input_file_spec> <output_path>'
    sys.exit(-1)

  input_file_spec = argv[1]
  output_file_path = argv[2]

  file_number = 1
  file_path = input_file_spec % file_number
  while os.path.exists(file_path):
    output_root_file = os.path.splitext(os.path.basename(file_path))[0]
    output_path = os.path.join(output_file_path, output_root_file + '.tiff')
    print 'processing %s to %s' % (file_path, output_path)
    img = Image(filename=file_path)
    # remove any letterboxing from top and bottom, unfortunately this eats other
    # elements too which can end up interfering negatively with cropping
#    trimmer = img.clone()
#    trimmer.trim()
#    if trimmer.size[0] > 1:
#      img = trimmer
#      img.reset_coords()
    # resize to 180px tall at original aspect ratio
    original_size = img.size
    scale = 192.0 / float(original_size[1])
    scale_width = int(scale * float(original_size[0]))
    # always make even width for centering, etc.
#    if scale_width % 2 == 1:
#      scale_width -= 1
    img.resize(width=scale_width, height=192)
    img.save(filename=output_path)
    file_number += 1
    file_path = input_file_spec % file_number
开发者ID:lnihlen,项目名称:vcsmc,代码行数:35,代码来源:preprocess_images.py

示例14: _create_proxy_rawpy

    def _create_proxy_rawpy(self, source, dest, mode):
        # maybe Pillow supports this file type directly?
        if not self.image:
            try:
                self.image = Image.open(source)
            except IOError:
                pass
            except Exception as e:
                logging.error('cannot read {}: {}'.format(source, e.args[0]))
                raise e

        # obviously not, try decoding as Raw
        if not self.image:
            try:
                raw = rawpy.imread(source)
                rgb = raw.postprocess(use_camera_wb=True, no_auto_bright=True)
                self.image = Image.fromarray(rgb)
            except Exception as e:
                logging.error('cannot read {}: {}'.format(source, e.args[0]))
                raise e

        image = self.image.copy()
        if mode == self.PROXY_FULLSIZE:
            pass
        elif mode == self.PROXY_THUMBNAIL:
            image.thumbnail(settings.THUMBNAILSIZE)
        elif mode == self.PROXY_WEBSIZED:
            image.thumbnail(settings.WEBSIZE)

        try:
            image.save(dest)
        except Exception as e:
            logging.error('cannot write {}: {}'.format(dest, e.args[0]))
开发者ID:woelfisch,项目名称:YoteCache,代码行数:33,代码来源:importer.py

示例15: convert_pdf_to_img

def convert_pdf_to_img(blob, img_type="jpg", quality=75, resolution=200):
    """
    Converts PDF with multiple pages into one image.
    It needs the file content NOT the filename or ioBytes and returns the image content.
    Note: It has memory leak!!
    http://stackoverflow.com/a/26233785/1497443

    Example:

    with open('my.pdf', "r") as f:
        file_content = f.read()

    # import ipdb
    # ipdb.set_trace()
    hh = convert_pdf_to_jpg(file_content)

    with open('my.jpg', 'wb') as f:
        f.write(hh)
    """
    from wand.image import Image as WandImage
    from wand.color import Color as WandColor

    pdf = WandImage(blob=blob, resolution=resolution)

    pages = len(pdf.sequence)

    wimage = WandImage(width=pdf.width, height=pdf.height * pages, background=WandColor("white"))

    for i in xrange(pages):
        wimage.composite(pdf.sequence[i], top=pdf.height * i, left=0)

    if img_type == "jpg":
        wimage.compression_quality = quality

    return wimage.make_blob(img_type)
开发者ID:giussepi,项目名称:django-generic-utils,代码行数:35,代码来源:functions.py


注:本文中的wand.image.Image类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。