• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python image.Image类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: scale

def scale(imagePath, face):
  # cloneImg.save(filename='{0}-{1}.jpg'.format(imagePath, i))

  face_x, face_y, face_w, face_h = face

  with Image(filename=imagePath) as img:
    img_w = img.size[0]
    img_h = img.size[1]

    w_delta = ((img_w - face_w) / 2) / NUM_IMAGES
    h_delta = ((img_h - face_h) / 2) / NUM_IMAGES

    gifImg = Image()

    for i in range(NUM_IMAGES, -1, -1):
      with img.clone() as cloneImg:
        if i == 0:
          cloneImg.crop(face_x, face_y, width=face_w, height=face_h)
          cloneImg.transform(resize='%dx%d' % (img_w, img_h))
        else:
          left = max(0, face_x - i * w_delta)
          top = max(0, face_y - i * h_delta)
          right = min(img_w, face_x + face_w + i * w_delta)
          bottom = min(img_h, face_y + face_h + i * h_delta)

          cloneImg.crop(left, top, right, bottom)
          cloneImg.transform(resize='%dx%d' % (img_w, img_h))
        gifImg.sequence.append(cloneImg)

    for frame in gifImg.sequence:
      with frame:
        frame.delay = 20
    gifImg.save(filename='%s.gif' % imagePath)
    gifImg.close()
    return '%s.gif' % imagePath
开发者ID:karan,项目名称:slashZoomEnhance,代码行数:35,代码来源:face_detect.py


示例17: main

def main():
    funky_img = Image(filename="../images/funky_illustration.png")
    funky_img = resize_to_percent(funky_img, 60)

    cropped_img = funky_img.clone()
    cropped_img.crop(top=0, left=275, width=340, height=486)

    display(funky_img)
    display(cropped_img)
开发者ID:zastre,项目名称:sandboxattempt,代码行数:9,代码来源:exp02.py


示例18: pdf_preview

def pdf_preview(tmp_file_path, tmp_dir):
    if use_generic_pdf_cover:
        return None
    else:
        if use_PIL:
            try:
                input1 = PdfFileReader(open(tmp_file_path, 'rb'), strict=False)
                page0 = input1.getPage(0)
                xObject = page0['/Resources']['/XObject'].getObject()

                for obj in xObject:
                    if xObject[obj]['/Subtype'] == '/Image':
                        size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
                        data = xObject[obj]._data # xObject[obj].getData()
                        if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
                            mode = "RGB"
                        else:
                            mode = "P"
                        if '/Filter' in xObject[obj]:
                            if xObject[obj]['/Filter'] == '/FlateDecode':
                                img = Image.frombytes(mode, size, data)
                                cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.png"
                                img.save(filename=os.path.join(tmp_dir, cover_file_name))
                                return cover_file_name
                                # img.save(obj[1:] + ".png")
                            elif xObject[obj]['/Filter'] == '/DCTDecode':
                                cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg"
                                img = open(cover_file_name, "wb")
                                img.write(data)
                                img.close()
                                return cover_file_name
                            elif xObject[obj]['/Filter'] == '/JPXDecode':
                                cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jp2"
                                img = open(cover_file_name, "wb")
                                img.write(data)
                                img.close()
                                return cover_file_name
                        else:
                            img = Image.frombytes(mode, size, data)
                            cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.png"
                            img.save(filename=os.path.join(tmp_dir, cover_file_name))
                            return cover_file_name
            except Exception as ex:
                print(ex)
        try:
            cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg"
            with Image(filename=tmp_file_path + "[0]", resolution=150) as img:
                img.compression_quality = 88
                img.save(filename=os.path.join(tmp_dir, cover_file_name))
            return cover_file_name
        except PolicyError as ex:
            logger.warning('Pdf extraction forbidden by Imagemagick policy: %s', ex)
            return None
        except Exception as ex:
            logger.warning('Cannot extract cover image, using default: %s', ex)
            return None
开发者ID:zack-chen,项目名称:calibre-web,代码行数:56,代码来源:book_formats.py


示例19: pdf2img

def pdf2img(pdf_path):
    #print "entered pdf2img"
    #print "CONVERTING SCALED PDF TO AN IMAGE"
    #print "---------------------------------------------------"
    img = Image(filename=pdf_path)
    imgname=pdf_path[:pdf_path.rindex('.')]+ext
    #print "SAVING CONVERTED IMAGE AS: "+imgname[imgname.rindex('/')+1:]
    #print "---------------------------------------------------"
    img.save(filename=imgname)
    return imgname
开发者ID:wantsomechocolate,项目名称:PDF2EXCEL,代码行数:10,代码来源:pdf2xls.py


示例20: cache_blob

    def cache_blob(self, blob_data, checkout_id, filename):
        """ Write a blob of data to disk according to the specified
        checkout id and filename.
        """

        thumbs_dir = "cookbook/assets/img/thumbnails"
        new_img = Image(blob=blob_data)
        thumb_file = "%s/%s_%s" % (thumbs_dir, checkout_id, filename)
        log.info("save thumbnail to: %s", thumb_file)
        new_img.save(filename=thumb_file)
开发者ID:WasatchPhotonics,项目名称:CookBook,代码行数:10,代码来源:views.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python warara.check_logged_in函数代码示例发布时间:2022-05-26
下一篇:
Python compat.nested函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap