Python utils.save_image() Examples

The following are 30 code examples of utils.save_image(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module utils , or try the search function .
Example #1
Source File: model_rotator.py    From object_detection_with_tensorflow with MIT License 6 votes vote down vote up
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
                    output_images, pred_images, pred_masks):
  """Function called by TF to save the prediction periodically."""

  def write_grid(grid, global_step):
    """Native python function to call for writing images to files."""
    if global_step % summary_freq == 0:
      img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
      utils.save_image(grid, img_path)
    return 0

  grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
  slim.summaries.add_image_summary(
      tf.expand_dims(grid, axis=0), name='grid_vis')
  save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
                       'write_grid')[0]
  return save_op 
Example #2
Source File: stylize_image.py    From fast-style-transfer with GNU General Public License v3.0 6 votes vote down vote up
def main():
    parser = build_parser()
    options = parser.parse_args()
    check_opts(options)

    network = options.network_path
    if not os.path.isdir(network):
        parser.error("Network %s does not exist." % network)

    content_image = utils.load_image(options.content)
    reshaped_content_height = (content_image.shape[0] - content_image.shape[0] % 4)
    reshaped_content_width = (content_image.shape[1] - content_image.shape[1] % 4)
    reshaped_content_image = content_image[:reshaped_content_height, :reshaped_content_width, :]
    reshaped_content_image = np.ndarray.reshape(reshaped_content_image, (1,) + reshaped_content_image.shape)

    prediction = ffwd(reshaped_content_image, network)
    utils.save_image(prediction, options.output_path) 
Example #3
Source File: rodent.py    From rodent with MIT License 6 votes vote down vote up
def start_camera(camera, folder, interval, until=None):
    """
    Start taking pictures every interval.
    If until is specified, it will take pictures
    until that time is reached (24h format).
    Needs to be of the following format: HH:MM
    """
    utils.clear_directory(folder)
    number = 0

    while True:
        _, image = camera.read()
        now = datetime.datetime.now()

        number += 1
        print 'Taking picture number %d at %s' % (number, now.isoformat())
        utils.save_image(image, folder, now)

        if utils.time_over(until, now):
            break

        time.sleep(interval)

    del(camera) 
Example #4
Source File: model_rotator.py    From yolo_v2 with Apache License 2.0 6 votes vote down vote up
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
                    output_images, pred_images, pred_masks):
  """Function called by TF to save the prediction periodically."""

  def write_grid(grid, global_step):
    """Native python function to call for writing images to files."""
    if global_step % summary_freq == 0:
      img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
      utils.save_image(grid, img_path)
    return 0

  grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
  slim.summaries.add_image_summary(
      tf.expand_dims(grid, axis=0), name='grid_vis')
  save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
                       'write_grid')[0]
  return save_op 
Example #5
Source File: model_rotator.py    From multilabel-image-classification-tensorflow with MIT License 6 votes vote down vote up
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
                    output_images, pred_images, pred_masks):
  """Function called by TF to save the prediction periodically."""

  def write_grid(grid, global_step):
    """Native python function to call for writing images to files."""
    if global_step % summary_freq == 0:
      img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
      utils.save_image(grid, img_path)
    return 0

  grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
  slim.summaries.add_image_summary(
      tf.expand_dims(grid, axis=0), name='grid_vis')
  save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
                       'write_grid')[0]
  return save_op 
Example #6
Source File: model_rotator.py    From Gun-Detector with Apache License 2.0 6 votes vote down vote up
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
                    output_images, pred_images, pred_masks):
  """Function called by TF to save the prediction periodically."""

  def write_grid(grid, global_step):
    """Native python function to call for writing images to files."""
    if global_step % summary_freq == 0:
      img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
      utils.save_image(grid, img_path)
    return 0

  grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
  slim.summaries.add_image_summary(
      tf.expand_dims(grid, axis=0), name='grid_vis')
  save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
                       'write_grid')[0]
  return save_op 
Example #7
Source File: model_rotator.py    From models with Apache License 2.0 6 votes vote down vote up
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
                    output_images, pred_images, pred_masks):
  """Function called by TF to save the prediction periodically."""

  def write_grid(grid, global_step):
    """Native python function to call for writing images to files."""
    if global_step % summary_freq == 0:
      img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
      utils.save_image(grid, img_path)
    return 0

  grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
  slim.summaries.add_image_summary(
      tf.expand_dims(grid, axis=0), name='grid_vis')
  save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
                       'write_grid')[0]
  return save_op 
Example #8
Source File: model_rotator.py    From object_detection_kitti with Apache License 2.0 6 votes vote down vote up
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
                    output_images, pred_images, pred_masks):
  """Function called by TF to save the prediction periodically."""

  def write_grid(grid, global_step):
    """Native python function to call for writing images to files."""
    if global_step % summary_freq == 0:
      img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
      utils.save_image(grid, img_path)
    return 0

  grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
  slim.summaries.add_image_summary(
      tf.expand_dims(grid, axis=0), name='grid_vis')
  save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
                       'write_grid')[0]
  return save_op 
Example #9
Source File: neural_style.py    From pytorch-multiple-style-transfer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def stylize(args):
    device = torch.device("cuda" if args.cuda else "cpu")

    content_image = utils.load_image(args.content_image, scale=args.content_scale)
    content_transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Lambda(lambda x: x.mul(255))
    ])
    content_image = content_transform(content_image)
    content_image = content_image.unsqueeze(0).to(device)


    with torch.no_grad():
        style_model = TransformerNet(style_num=args.style_num)
        state_dict = torch.load(args.model)
        style_model.load_state_dict(state_dict)
        style_model.to(device)
        output = style_model(content_image, style_id = [args.style_id]).cpu()

    utils.save_image('output/'+args.output_image+'_style'+str(args.style_id)+'.jpg', output[0]) 
Example #10
Source File: model_rotator.py    From hands-detection with MIT License 6 votes vote down vote up
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
                    output_images, pred_images, pred_masks):
  """Function called by TF to save the prediction periodically."""

  def write_grid(grid, global_step):
    """Native python function to call for writing images to files."""
    if global_step % summary_freq == 0:
      img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
      utils.save_image(grid, img_path)
    return 0

  grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
  slim.summaries.add_image_summary(
      tf.expand_dims(grid, axis=0), name='grid_vis')
  save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
                       'write_grid')[0]
  return save_op 
Example #11
Source File: model_rotator.py    From g-tensorflow-models with Apache License 2.0 6 votes vote down vote up
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
                    output_images, pred_images, pred_masks):
  """Function called by TF to save the prediction periodically."""

  def write_grid(grid, global_step):
    """Native python function to call for writing images to files."""
    if global_step % summary_freq == 0:
      img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
      utils.save_image(grid, img_path)
    return 0

  grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
  slim.summaries.add_image_summary(
      tf.expand_dims(grid, axis=0), name='grid_vis')
  save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
                       'write_grid')[0]
  return save_op 
Example #12
Source File: model_ptn.py    From g-tensorflow-models with Apache License 2.0 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      input_voxels=None,
                      output_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, global_step,
                   input_voxels, output_voxels):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(
          input_images,
          gt_projs,
          pred_projs,
          input_voxels=input_voxels,
          output_voxels=output_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
      return grid

    save_op = tf.py_func(write_grid, [
        input_images, gt_projs, pred_projs, global_step, input_voxels,
        output_voxels
    ], [tf.uint8], 'write_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_op, axis=0), name='grid_vis')
    return save_op 
Example #13
Source File: model_voxel_generation.py    From object_detection_with_tensorflow with MIT License 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      pred_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, pred_voxels,
                   global_step):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
        with open(
            os.path.join(log_dir, 'pred_voxels_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, pred_voxels)
        with open(
            os.path.join(log_dir, 'input_images_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, input_images)

      return grid

    py_func_args = [
        input_images, gt_projs, pred_projs, pred_voxels, global_step
    ]
    save_grid_op = tf.py_func(write_grid, py_func_args, [tf.uint8],
                              'wrtie_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_grid_op, axis=0), name='grid_vis')
    return save_grid_op 
Example #14
Source File: neural_style.py    From ignite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stylize(args):
    device = torch.device("cuda" if args.cuda else "cpu")

    content_transform = transforms.Compose([transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255))])

    content_image = utils.load_image(args.content_image, scale=args.content_scale)
    content_image = content_transform(content_image)
    content_image = content_image.unsqueeze(0).to(device)

    with torch.no_grad():
        style_model = torch.load(args.model)
        style_model.to(device)
        output = style_model(content_image).cpu()
        utils.save_image(args.output_image, output[0]) 
Example #15
Source File: evaluate.py    From DDRNet with MIT License 5 votes vote down vote up
def loop_body_patch(it, ckpt_path, depth_in, depth_ref, color, mask, config):
    """
    :param depth_ref: unused yet. offline quantitative evaluation of depth_dt. 
    """
    print(time.ctime())
    print("Load checkpoint: {}".format(ckpt_path))

    h, w = depth_in.shape[:2]
    low_thres = config.low_thres
    up_thres = config.up_thres
    thres_range = (up_thres - low_thres) / 2.0

    params = build_model(h, w, config)
    # ckpt_step = ckpt_path.split("/")[-1]

    sess = tf.Session()
    load_from_checkpoint(sess, ckpt_path)

    depth_dn_im, depth_dt_im = sess.run([params["depth_dn"], params["depth_dt"]],
                                        feed_dict={params["depth_in"]: depth_in.reshape(1, h, w, 1),
                                                   params["color"]: color.reshape(1, h, w, 1),
                                                   params["is_training"]: False})

    depth_dn_im = (((depth_dn_im + 1.0) * thres_range + low_thres) * mask).astype(np.uint16)
    depth_dt_im = (((depth_dt_im + 1.0) * thres_range + low_thres) * mask).astype(np.uint16)

    utils.save_image(depth_dn_im, config.sample_dir, "frame_{}_dn.png".format(it))
    utils.save_image(depth_dt_im, config.sample_dir, "frame_{}_dt.png".format(it))

    tf.reset_default_graph()
    print("saving img {}.".format(it)) 
Example #16
Source File: evaluate.py    From DDRNet with MIT License 5 votes vote down vote up
def loop_body_whole(it, ckpt_path, raw_arr, gt_arr, rgb_arr, H, W, config):
    """
    forward input raw_array patches seperately, then h_stack and v_stack these patches into whole.
    """
    print(time.ctime())
    print("Load checkpoint: {}".format(ckpt_path))

    h, w = raw_arr[0][0].shape[:2]
    low_thres = config.low_thres
    up_thres = config.up_thres
    thres_range = (up_thres - low_thres) / 2.0

    params = build_model(h, w, config)
    ckpt_step = ckpt_path.split("/")[-1]

    sess = tf.Session()
    load_from_checkpoint(sess, ckpt_path)

    dn_arr = []
    for i, h_list in enumerate(raw_arr):
        dn_h_list = []
        for j in range(len(h_list)):
            depth_dn_patch, depth_dt_patch = sess.run([params["depth_dn"], params["depth_dt"]],
                                                feed_dict={params["depth_in"]: depth_in.reshape(1, h, w, 1),
                                                           params["color"]: color.reshape(1, h, w, 1),
                                                           params["is_training"]: False})
            dn_h_list.append(depth_dn_patch)
        dn_arr.append(dn_h_list)
    dn_im = utils.stack_patch(dn_arr, H, W)
    dn_im = ((dn_im + 1.0) * thres_range + low_thres).astype(np.uint16)
    utils.save_image(dn_im, config.sample_dir, "frame_{}_dn.png".format(it))

    tf.reset_default_graph()
    print("saving img {}.".format(it)) 
Example #17
Source File: evaluate.py    From DDRNet with MIT License 5 votes vote down vote up
def loop_body_patch_time(sess, name, params, depth_in, color, mask, config):
    """
    Build test graph only once, more efficient when training phase is finished.
    :return: time elapsed for one batch of testing image.
    """
    h, w = depth_in.shape[:2]
    depth_in = depth_in.reshape(1, h, w, 1)
    color = color.reshape(1, h, w, 1)

    low_thres = config.low_thres
    up_thres = config.up_thres
    thres_range = (up_thres - low_thres) / 2.0

    t_start = time.time()
    feed_dict = {params["depth_in"]: depth_in,
                 params["color"]: color,
                 params["is_training"]: False}
    depth_dn_im = depth_dt_im = None
    if (params["depth_dn"] is not None) and (params["depth_dt"] is not None):
        depth_dn_im, depth_dt_im = sess.run([params["depth_dn"], params["depth_dt"]],
                                            feed_dict=feed_dict)
    elif (params["depth_dn"] is not None):
        depth_dn_im = sess.run(params["depth_dn"], feed_dict=feed_dict)
    elif (params["depth_dt"] is not None):
        depth_dt_im = sess.run(params["depth_dt"], feed_dict=feed_dict)

    print("saving img {}.".format(name))
    if depth_dn_im is not None:
        depth_dn_im = (((depth_dn_im + 1.0) * thres_range + low_thres) * mask).astype(np.uint16)
        utils.save_image(depth_dn_im, config.sample_dir, "dn_{}".format(name))
    if depth_dt_im is not None:
        depth_dt_im = (((depth_dt_im + 1.0) * thres_range + low_thres) * mask).astype(np.uint16)
        utils.save_image(depth_dt_im, config.sample_dir, "dt_{}".format(name))
    t_end = time.time()
    return (t_end - t_start) 
Example #18
Source File: neural_style.py    From PyTorch with MIT License 5 votes vote down vote up
def stylize(args):
    device = torch.device("cuda" if args.cuda else "cpu")

    content_image = utils.load_image(args.content_image, scale=args.content_scale)
    content_transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Lambda(lambda x: x.mul(255))
    ])
    content_image = content_transform(content_image)
    content_image = content_image.unsqueeze(0).to(device)

    if args.model.endswith(".onnx"):
        output = stylize_onnx_caffe2(content_image, args)
    else:
        with torch.no_grad():
            style_model = TransformerNet()
            state_dict = torch.load(args.model)
            # remove saved deprecated running_* keys in InstanceNorm from the checkpoint
            for k in list(state_dict.keys()):
                if re.search(r'in\d+\.running_(mean|var)$', k):
                    del state_dict[k]
            style_model.load_state_dict(state_dict)
            style_model.to(device)
            if args.export_onnx:
                assert args.export_onnx.endswith(".onnx"), "Export model file should end with .onnx"
                output = torch.onnx._export(style_model, content_image, args.export_onnx).cpu()
            else:
                output = style_model(content_image).cpu()
    utils.save_image(args.output_image, output[0]) 
Example #19
Source File: model_voxel_generation.py    From g-tensorflow-models with Apache License 2.0 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      pred_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, pred_voxels,
                   global_step):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
        with open(
            os.path.join(log_dir, 'pred_voxels_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, pred_voxels)
        with open(
            os.path.join(log_dir, 'input_images_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, input_images)

      return grid

    py_func_args = [
        input_images, gt_projs, pred_projs, pred_voxels, global_step
    ]
    save_grid_op = tf.py_func(write_grid, py_func_args, [tf.uint8],
                              'wrtie_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_grid_op, axis=0), name='grid_vis')
    return save_grid_op 
Example #20
Source File: model_ptn.py    From models with Apache License 2.0 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      input_voxels=None,
                      output_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, global_step,
                   input_voxels, output_voxels):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(
          input_images,
          gt_projs,
          pred_projs,
          input_voxels=input_voxels,
          output_voxels=output_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
      return grid

    save_op = tf.py_func(write_grid, [
        input_images, gt_projs, pred_projs, global_step, input_voxels,
        output_voxels
    ], [tf.uint8], 'write_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_op, axis=0), name='grid_vis')
    return save_op 
Example #21
Source File: model_voxel_generation.py    From models with Apache License 2.0 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      pred_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, pred_voxels,
                   global_step):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
        with open(
            os.path.join(log_dir, 'pred_voxels_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, pred_voxels)
        with open(
            os.path.join(log_dir, 'input_images_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, input_images)

      return grid

    py_func_args = [
        input_images, gt_projs, pred_projs, pred_voxels, global_step
    ]
    save_grid_op = tf.py_func(write_grid, py_func_args, [tf.uint8],
                              'wrtie_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_grid_op, axis=0), name='grid_vis')
    return save_grid_op 
Example #22
Source File: model_ptn.py    From multilabel-image-classification-tensorflow with MIT License 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      input_voxels=None,
                      output_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, global_step,
                   input_voxels, output_voxels):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(
          input_images,
          gt_projs,
          pred_projs,
          input_voxels=input_voxels,
          output_voxels=output_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
      return grid

    save_op = tf.py_func(write_grid, [
        input_images, gt_projs, pred_projs, global_step, input_voxels,
        output_voxels
    ], [tf.uint8], 'write_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_op, axis=0), name='grid_vis')
    return save_op 
Example #23
Source File: model_voxel_generation.py    From multilabel-image-classification-tensorflow with MIT License 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      pred_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, pred_voxels,
                   global_step):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
        with open(
            os.path.join(log_dir, 'pred_voxels_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, pred_voxels)
        with open(
            os.path.join(log_dir, 'input_images_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, input_images)

      return grid

    py_func_args = [
        input_images, gt_projs, pred_projs, pred_voxels, global_step
    ]
    save_grid_op = tf.py_func(write_grid, py_func_args, [tf.uint8],
                              'wrtie_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_grid_op, axis=0), name='grid_vis')
    return save_grid_op 
Example #24
Source File: model_voxel_generation.py    From Gun-Detector with Apache License 2.0 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      pred_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, pred_voxels,
                   global_step):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
        with open(
            os.path.join(log_dir, 'pred_voxels_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, pred_voxels)
        with open(
            os.path.join(log_dir, 'input_images_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, input_images)

      return grid

    py_func_args = [
        input_images, gt_projs, pred_projs, pred_voxels, global_step
    ]
    save_grid_op = tf.py_func(write_grid, py_func_args, [tf.uint8],
                              'wrtie_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_grid_op, axis=0), name='grid_vis')
    return save_grid_op 
Example #25
Source File: rodent.py    From rodent with MIT License 5 votes vote down vote up
def motion_detection(camera, folder, until):
    """
    Uses 3 frames to look for motion, can't remember where
    I found it but it gives better result than my first try
    with comparing 2 frames.
    """
    utils.clear_directory(folder)

    # Need to get 2 images to start with
    previous_image = cv2.cvtColor(camera.read()[1], cv2.cv.CV_RGB2GRAY)
    current_image = cv2.cvtColor(camera.read()[1], cv2.cv.CV_RGB2GRAY)
    purple = (140, 25, 71)

    while True:
        now = datetime.datetime.now()
        _, image = camera.read()
        gray_image = cv2.cvtColor(image, cv2.cv.CV_RGB2GRAY)

        difference1 = cv2.absdiff(previous_image, gray_image)
        difference2 = cv2.absdiff(current_image, gray_image)
        result = cv2.bitwise_and(difference1, difference2)

        # Basic threshold, turn the bitwise_and into a black or white (haha)
        # result, white (255) being a motion
        _, result = cv2.threshold(result, 40, 255, cv2.THRESH_BINARY)

        # Let's show a square around the detected motion in the original pic
        low_point, high_point = utils.find_motion_boundaries(result.tolist())
        if low_point is not None and high_point is not None:
            cv2.rectangle(image, low_point, high_point, purple, 3)
            print 'Motion detected ! Taking picture'
            utils.save_image(image, folder, now)

        previous_image = current_image
        current_image = gray_image

        if utils.time_over(until, now):
            break

    del(camera) 
Example #26
Source File: analogy.py    From chainer-PGGAN with MIT License 5 votes vote down vote up
def generate():
    parser = argparse.ArgumentParser()
    parser.add_argument('--gpu', '-g', type=int, default=-1)
    parser.add_argument('--gen', type=str, default=None)
    parser.add_argument('--depth', '-d', type=int, default=0)
    parser.add_argument('--out', '-o', type=str, default='img/')
    parser.add_argument('--num', '-n', type=int, default=10)
    args = parser.parse_args()
    
    gen = network.Generator(depth=args.depth)
    print('loading generator model from ' + args.gen)
    serializers.load_npz(args.gen, gen)

    if args.gpu >= 0:
        cuda.get_device_from_id(0).use()
        gen.to_gpu()

    xp = gen.xp
        
    z1 = gen.z(1)
    z2 = gen.z(1)

    for i in range(args.num):
        print(i)
        p = i / (args.num-1)
        z = z1 * p + z2 * (1 - p)
        x = gen(z, alpha=1.0)
        x = chainer.cuda.to_cpu(x.data)
        
        img = x[0].copy()
        filename = os.path.join(args.out, 'gen_%04d.png'%i)
        utils.save_image(img, filename) 
Example #27
Source File: model_ptn.py    From yolo_v2 with Apache License 2.0 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      input_voxels=None,
                      output_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, global_step,
                   input_voxels, output_voxels):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(
          input_images,
          gt_projs,
          pred_projs,
          input_voxels=input_voxels,
          output_voxels=output_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
      return grid

    save_op = tf.py_func(write_grid, [
        input_images, gt_projs, pred_projs, global_step, input_voxels,
        output_voxels
    ], [tf.uint8], 'write_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_op, axis=0), name='grid_vis')
    return save_op 
Example #28
Source File: model_voxel_generation.py    From yolo_v2 with Apache License 2.0 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      pred_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, pred_voxels,
                   global_step):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
        with open(
            os.path.join(log_dir, 'pred_voxels_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, pred_voxels)
        with open(
            os.path.join(log_dir, 'input_images_%s' % str(global_step)),
            'w') as fout:
          np.save(fout, input_images)

      return grid

    py_func_args = [
        input_images, gt_projs, pred_projs, pred_voxels, global_step
    ]
    save_grid_op = tf.py_func(write_grid, py_func_args, [tf.uint8],
                              'wrtie_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_grid_op, axis=0), name='grid_vis')
    return save_grid_op 
Example #29
Source File: model_ptn.py    From Gun-Detector with Apache License 2.0 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      input_voxels=None,
                      output_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, global_step,
                   input_voxels, output_voxels):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(
          input_images,
          gt_projs,
          pred_projs,
          input_voxels=input_voxels,
          output_voxels=output_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
      return grid

    save_op = tf.py_func(write_grid, [
        input_images, gt_projs, pred_projs, global_step, input_voxels,
        output_voxels
    ], [tf.uint8], 'write_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_op, axis=0), name='grid_vis')
    return save_op 
Example #30
Source File: model_ptn.py    From object_detection_with_tensorflow with MIT License 5 votes vote down vote up
def write_disk_grid(self,
                      global_step,
                      log_dir,
                      input_images,
                      gt_projs,
                      pred_projs,
                      input_voxels=None,
                      output_voxels=None):
    """Function called by TF to save the prediction periodically."""
    summary_freq = self._params.save_every

    def write_grid(input_images, gt_projs, pred_projs, global_step,
                   input_voxels, output_voxels):
      """Native python function to call for writing images to files."""
      grid = _build_image_grid(
          input_images,
          gt_projs,
          pred_projs,
          input_voxels=input_voxels,
          output_voxels=output_voxels)

      if global_step % summary_freq == 0:
        img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
        utils.save_image(grid, img_path)
      return grid

    save_op = tf.py_func(write_grid, [
        input_images, gt_projs, pred_projs, global_step, input_voxels,
        output_voxels
    ], [tf.uint8], 'write_grid')[0]
    slim.summaries.add_image_summary(
        tf.expand_dims(save_op, axis=0), name='grid_vis')
    return save_op