Generate images.

    Parameters
    ----------
    args : `argparse.Namespace`
        Command arguments.
490440
def cmd_generate(args):
    
    check_output_format(args.output, args.count)

    markov = load(MarkovImage, args.state, args)

    if args.size is None:
        if markov.scanner.resize is None:
            print('Unknown output image size', file=stderr)
            exit(1)
        width, height = markov.scanner.resize
    else:
        width, height = args.size

    if args.level is None:
        scale = markov.scanner.min_size
    else:
        scale = reduce(
            lambda x, y: x * y,
            islice(markov.scanner.level_scale, 0, args.level - 1),
            1
        )

    width, height = width // scale, height // scale

    markov.scanner.traversal[0].show_progress = args.progress

    for fname in outfiles(markov, args.output, args.count, args.progress):
        img = markov(
            width, height,
            state_size=args.state_size,
            levels=args.level
        )
        save_image(img, fname)
968899
def [](*args)
      a = @images[*args]
      if a.respond_to?(:each)
        ilist = self.class.new
        a.each { |image| ilist << image }
        a = ilist
      end
      a
    end
141343
def write(self)->None:
        ""
        orig_images, gen_images, real_images = self._get_image_tensors()
        self._write_images(name='orig images', images=orig_images)
        self._write_images(name='gen images',  images=gen_images)
        self._write_images(name='real images', images=real_images)
880177
def generate_example():
    
    cmd_args = sys.argv[1:]
    parser = argparse.ArgumentParser(description='Confpy example generator.')
    parser.add_argument(
        '--module',
        action='append',
        help='A python module which should be imported.',
    )
    parser.add_argument(
        '--file',
        action='append',
        help='A python file which should be evaled.',
    )
    parser.add_argument(
        '--format',
        default='JSON',
        choices=('JSON', 'INI'),
        help='The output format of the configuration file.',
    )

    args = parser.parse_args(cmd_args)

    for module in args.module or ():

        __import__(module)

    for source_file in args.file or ():

        cfg = pyfile.PythonFile(path=source_file).config

    cfg = config.Configuration()

    print(example.generate_example(cfg, ext=args.format))
1039713
def generate(self, chars, format='png'):
        
        im = self.generate_image(chars)
        out = BytesIO()
        im.save(out, format=format)
        out.seek(0)
        return out
136373
def _generate_example(self, data_path, image_id):
    """"""
    image_filepath = os.path.join(
        data_path, "VOCdevkit/VOC2007/JPEGImages", "{}.jpg".format(image_id))
    annon_filepath = os.path.join(
        data_path, "VOCdevkit/VOC2007/Annotations", "{}.xml".format(image_id))

    def _get_example_objects():
      """Function to get all the objects from the annotation XML file."""
      with tf.io.gfile.GFile(annon_filepath, "r") as f:
        root = xml.etree.ElementTree.parse(f).getroot()

        size = root.find("size")
        width = float(size.find("width").text)
        height = float(size.find("height").text)

        for obj in root.findall("object"):
          # Get object's label name.
          label = obj.find("name").text.lower()
          # Get objects' pose name.
          pose = obj.find("pose").text.lower()
          is_truncated = (obj.find("truncated").text == "1")
          is_difficult = (obj.find("difficult").text == "1")
          bndbox = obj.find("bndbox")
          xmax = float(bndbox.find("xmax").text)
          xmin = float(bndbox.find("xmin").text)
          ymax = float(bndbox.find("ymax").text)
          ymin = float(bndbox.find("ymin").text)
          yield {
              "label": label,
              "pose": pose,
              "bbox": tfds.features.BBox(
                  ymin / height, xmin / width, ymax / height, xmax / width),
              "is_truncated": is_truncated,
              "is_difficult": is_difficult,
          }

    objects = list(_get_example_objects())
    # Use set() to remove duplicates
    labels = sorted(set(obj["label"] for obj in objects))
    labels_no_difficult = sorted(set(
        obj["label"] for obj in objects if obj["is_difficult"] == 0
    ))
    return {
        "image": image_filepath,
        "image/filename": image_id + ".jpg",
        "objects": objects,
        "labels": labels,
        "labels_no_difficult": labels_no_difficult,
    }
165644
def generate(self, **kwargs: Any) -> bytes:
        """"""
        namespace = {
            "escape": escape.xhtml_escape,
            "xhtml_escape": escape.xhtml_escape,
            "url_escape": escape.url_escape,
            "json_encode": escape.json_encode,
            "squeeze": escape.squeeze,
            "linkify": escape.linkify,
            "datetime": datetime,
            "_tt_utf8": escape.utf8,  # for internal use
            "_tt_string_types": (unicode_type, bytes),
            # __name__ and __loader__ allow the traceback mechanism to find
            # the generated source code.
            "__name__": self.name.replace(".", "_"),
            "__loader__": ObjectDict(get_source=lambda name: self.code),
        }
        namespace.update(self.namespace)
        namespace.update(kwargs)
        exec_in(self.compiled, namespace)
        execute = typing.cast(Callable[[], bytes], namespace["_tt_execute"])
        # Clear the traceback module's cache of source data now that
        # we've generated a new template (mainly for this module's
        # unittests, where different tests reuse the same name).
        linecache.clearcache()
        return execute()
775283
def push_images(base_path, image_namespace, engine_obj, config, **kwargs):
    
    config_path = kwargs.get('config_path', engine_obj.auth_config_path)
    username = kwargs.get('username')
    password = kwargs.get('password')
    push_to = kwargs.get('push_to')
    url = engine_obj.default_registry_url
    registry_name = engine_obj.default_registry_name
    namespace = image_namespace
    save_conductor = config.save_conductor
    repository_prefix = None
    pull_from_url = None

    if push_to:
        if config.get('registries', dict()).get(push_to):
            url = config['registries'][push_to].get('url')
            namespace = config['registries'][push_to].get('namespace', namespace)
            repository_prefix = config['registries'][push_to].get('repository_prefix')
            pull_from_url = config['registries'][push_to].get('pull_from_url')
            if not url:
                raise AnsibleContainerRegistryAttributeException(
                    u"Registry {} missing required attribute 'url'".format(push_to)
                )
        else:
            url, namespace = resolve_push_to(push_to, engine_obj.default_registry_url, namespace)

    if username and not password:
        # If a username was supplied without a password, prompt for it
        if url != engine_obj.default_registry_url:
            registry_name = url
        while not password:
            password = getpass.getpass(u"Enter password for {0} at {1}: ".format(username, registry_name))

    if config_path:
        # Make sure the config_path exists
        #  - gives us a chance to create the file with correct permissions, if it does not exists
        #  - makes sure we mount a path to the conductor for a specific file
        config_path = os.path.normpath(os.path.expanduser(config_path))
        if os.path.exists(config_path) and os.path.isdir(config_path):
            raise AnsibleContainerException(
                u"Expecting --config-path to be a path to a file, not a directory"
            )
        elif not os.path.exists(config_path):
            # Make sure the directory path exists
            if not os.path.exists(os.path.dirname(config_path)):
                try:
                    os.makedirs(os.path.dirname(config_path), 0o750)
                except OSError:
                    raise AnsibleContainerException(
                        u"Failed to create the requested the path {}".format(os.path.dirname(config_path))
                    )
            # Touch the file
            open(config_path, 'w').close()

    # If you ran build with --save-build-container, then you're broken without first removing
    #  the old build container.
    remove_existing_container(engine_obj, 'conductor', remove_volumes=True)

    push_params = {}
    push_params.update(kwargs)
    push_params['config_path'] = config_path
    push_params['password'] = password
    push_params['url'] = url
    push_params['namespace'] = namespace
    push_params['repository_prefix'] = repository_prefix
    push_params['pull_from_url'] = pull_from_url

    # Push
    engine_obj.await_conductor_command('push', dict(config), base_path, push_params, save_container=save_conductor)

    return {'url': url,
            'namespace': namespace,
            'repository_prefix': repository_prefix,
            'pull_from_url': pull_from_url }
227116
def create_sprite_image(examples):
    

    def generate_image_from_thubnails(thumbnails, thumbnail_dims):
      """Generates a sprite atlas image from a set of thumbnails."""
      num_thumbnails = tf.shape(thumbnails)[0].eval()
      images_per_row = int(math.ceil(math.sqrt(num_thumbnails)))
      thumb_height = thumbnail_dims[0]
      thumb_width = thumbnail_dims[1]
      master_height = images_per_row * thumb_height
      master_width = images_per_row * thumb_width
      num_channels = 3
      master = np.zeros([master_height, master_width, num_channels])
      for idx, image in enumerate(thumbnails.eval()):
        left_idx = idx % images_per_row
        top_idx = int(math.floor(idx / images_per_row))
        left_start = left_idx * thumb_width
        left_end = left_start + thumb_width
        top_start = top_idx * thumb_height
        top_end = top_start + thumb_height
        master[top_start:top_end, left_start:left_end, :] = image
      return tf.image.encode_png(master)

    image_feature_name = 'image/encoded'
    sprite_thumbnail_dim_px = 32
    with tf.compat.v1.Session():
      keys_to_features = {
          image_feature_name:
              tf.FixedLenFeature((), tf.string, default_value=''),
      }
      parsed = tf.parse_example(examples, keys_to_features)
      images = tf.zeros([1, 1, 1, 1], tf.float32)
      i = tf.constant(0)
      thumbnail_dims = (sprite_thumbnail_dim_px,
                        sprite_thumbnail_dim_px)
      num_examples = tf.constant(len(examples))
      encoded_images = parsed[image_feature_name]

      # Loop over all examples, decoding the image feature value, resizing
      # and appending to a list of all images.
      def loop_body(i, encoded_images, images):
        encoded_image = encoded_images[i]
        image = tf.image.decode_jpeg(encoded_image, channels=3)
        resized_image = tf.image.resize(image, thumbnail_dims)
        expanded_image = tf.expand_dims(resized_image, 0)
        images = tf.cond(
            tf.equal(i, 0), lambda: expanded_image,
            lambda: tf.concat([images, expanded_image], 0))
        return i + 1, encoded_images, images

      loop_out = tf.while_loop(
          lambda i, encoded_images, images: tf.less(i, num_examples),
          loop_body, [i, encoded_images, images],
          shape_invariants=[
              i.get_shape(),
              encoded_images.get_shape(),
              tf.TensorShape(None)
          ])

      # Create the single sprite atlas image from these thumbnails.
      sprite = generate_image_from_thubnails(loop_out[2], thumbnail_dims)
      return sprite.eval()
869122
def create_image(self, image_file, caption):
        
        suffix = 'png'
        if image_file:
            img = Image.open(os.path.join(self.gallery, image_file))
            width, height = img.size
            ratio = width/WIDTH
            img = img.resize((int(width // ratio),
                              int(height // ratio)),
                             Image.ANTIALIAS)
        else:
            img = Image.new('RGB', (WIDTH, HEIGHT), 'black')
            image = self.add_caption(img, caption)
            
        image = img

        return image
446077
def create(self,image_path, size=1024, sudo=False):
    '''

    '''        
    from spython.utils import check_install
    check_install()


    cmd = self.init_command('image.create')
    cmd = cmd + ['--size', str(size), image_path ]

    output = self.run_command(cmd,sudo=sudo)
    self.println(output)

    if not os.path.exists(image_path):
        bot.exit("Could not create image %s" %image_path)

    return image_path
185768
def generate(self, api):
        """"""
        with self.output_to_relative_path('ex1.out'):
            for namespace in api.namespaces.values():
                self.emit(namespace.name)
319564
def main():
    

    init_logger()
    args = _parse_cli_args()

    if args.u:
        enter_api_key()
        return

    if args.O == GEVENT:
        args.O = _gevent_patch()

    set_image_size_mode(args.s)
    photoset_id = args.g
    global directory
    directory = args.d if args.d else photoset_id

    read_config()
    photos = get_photos_info(photoset_id)
    create_dir(directory)

    if args.O == SINGLE_PROCESS:
        single_download_photos(photos)
    elif args.O == GEVENT:
        event_download_photos(photos)
    elif args.O == MULTITHREAD:
        multithread_download_photos(photos)
    else:
        logger.error('Unknown Error')
939716
def main(_):
  """"""
  batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
  for filenames, images in load_images(FLAGS.input_dir, batch_shape):
    save_images(images, filenames, FLAGS.output_dir)
1076267
def generate(self, text):
        
        sizes = current_app.config['AVATARS_SIZE_TUPLE']
        path = current_app.config['AVATARS_SAVE_PATH']
        suffix = {sizes[0]: 's', sizes[1]: 'm', sizes[2]: 'l'}

        for size in sizes:
            image_byte_array = self.get_image(
                string=str(text),
                width=int(size),
                height=int(size),
                pad=int(size * 0.1))
            self.save(image_byte_array, save_location=os.path.join(path, '%s_%s.png' % (text, suffix[size])))
        return [text + '_s.png', text + '_m.png', text + '_l.png']
285892
def write(self, chars, output, format='png'):
        
        im = self.generate_image(chars)
        return im.save(output, format=format)
75581
def cli(yamlfile, format, dir, classes, img, noimages):
    
    MarkdownGenerator(yamlfile, format).serialize(classes=classes, directory=dir, image_dir=img, noimages=noimages)