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

Python tensorflow.read_file函数代码示例

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

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



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

示例1: read_images_from_disk

def read_images_from_disk(input_queue):
    """Consumes a single filename and label as a ' '-delimited string.
    Args:
      filenames for data and tensor
    Returns:
      Two tensors: the decoded image, and the string label.
    """

    img_filename = input_queue[0]
    label_filename = input_queue[1]

    img_data = tf.read_file(img_filename, name='read_image')
    img_tensor = tf.image.decode_png(img_data, channels=1)
    img_tensor = tf.reshape(img_tensor, [IMG_HEIGHT, IMG_WIDTH, 1])
    # transform to a float image
    img_tensor = tf.cast(img_tensor, tf.float32)
    # img_tensor = tf.zeros([IMG_HEIGHT, IMG_WIDTH, 1], dtype=tf.float32, name=None)


    label_data = tf.read_file(label_filename, name='read_label')
    label_tensor = tf.image.decode_png(label_data, channels=1)
    label_tensor = tf.reshape(label_tensor, [IMG_HEIGHT, IMG_WIDTH, 1])
    label_tensor = tf.cast(label_tensor, tf.float32)
    # label_tensor = tf.zeros([IMG_HEIGHT, IMG_WIDTH, 1], dtype=tf.float32, name=None)
    return img_tensor, label_tensor
开发者ID:mtourne,项目名称:nerveseg,代码行数:25,代码来源:nerveseg_input.py


示例2: _produce_one_sample

  def _produce_one_sample(self):
    dirname = os.path.dirname(self.path)
    if not check_dir(dirname):
      raise ValueError("Invalid data path.")
    with open(self.path, 'r') as fid:
      flist = [l.strip() for l in fid.xreadlines()]

    if self.shuffle:
      random.shuffle(flist)

    input_files = [os.path.join(dirname, 'input', f) for f in flist]
    output_files = [os.path.join(dirname, 'output', f) for f in flist]

    self.nsamples = len(input_files)

    input_queue, output_queue = tf.train.slice_input_producer(
        [input_files, output_files], shuffle=self.shuffle,
        seed=0123, num_epochs=self.num_epochs)

    if '16-bit' in magic.from_file(input_files[0]):
      input_dtype = tf.uint16
      input_wl = 65535.0
    else:
      input_wl = 255.0
      input_dtype = tf.uint8
    if '16-bit' in magic.from_file(output_files[0]):
      output_dtype = tf.uint16
      output_wl = 65535.0
    else:
      output_wl = 255.0
      output_dtype = tf.uint8

    input_file = tf.read_file(input_queue)
    output_file = tf.read_file(output_queue)

    if os.path.splitext(input_files[0])[-1] == '.jpg': 
      im_input = tf.image.decode_jpeg(input_file, channels=3)
    else:
      im_input = tf.image.decode_png(input_file, dtype=input_dtype, channels=3)

    if os.path.splitext(output_files[0])[-1] == '.jpg': 
      im_output = tf.image.decode_jpeg(output_file, channels=3)
    else:
      im_output = tf.image.decode_png(output_file, dtype=output_dtype, channels=3)

    # normalize input/output
    sample = {}
    with tf.name_scope('normalize_images'):
      im_input = tf.to_float(im_input)/input_wl
      im_output = tf.to_float(im_output)/output_wl

    inout = tf.concat([im_input, im_output], 2)
    fullres, inout = self._augment_data(inout, 6)

    sample['lowres_input'] = inout[:, :, :3]
    sample['lowres_output'] = inout[:, :, 3:]
    sample['image_input'] = fullres[:, :, :3]
    sample['image_output'] = fullres[:, :, 3:]
    return sample
开发者ID:KeyKy,项目名称:hdrnet,代码行数:59,代码来源:data_pipeline.py


示例3: _read_images

def _read_images(paths):
    with tf.name_scope("read_images"):
        path1, path2 = tf.decode_csv(paths, [[""], [""]], field_delim=" ")
        file_content1 = tf.read_file(path1)
        file_content2 = tf.read_file(path2)
        image1 = tf.cast(tf.image.decode_png(file_content1, channels=3, dtype=tf.uint8), tf.float32)
        image2 = tf.cast(tf.image.decode_png(file_content2, channels=3, dtype=tf.uint8), tf.float32)
        image1.set_shape(IMAGE_SHAPE)
        image2.set_shape(IMAGE_SHAPE)
    return image1, image2
开发者ID:vlpolyansky,项目名称:video-cnn,代码行数:10,代码来源:movie.py


示例4: read_and_decode

    def read_and_decode(self):
        image_name = tf.read_file(self.filename_queue[0])
        image = tf.image.decode_jpeg(image_name, channels = 3)
        image = tf.image.resize_images(image, 320, 480)
        image /= 255.

        label_name = tf.read_file(self.filename_queue[1])
        label = tf.image.decode_png(label_name, channels = 1)
        label = tf.image.resize_images(label, 320, 480)
        label = tf.to_int64(label > 0)

        return image, label
开发者ID:qingzew,项目名称:tensorflow-fcn,代码行数:12,代码来源:reader.py


示例5: CamVid_reader

def CamVid_reader(filename_queue):
    image_filename = filename_queue[0]
    label_filename = filename_queue[1]

    imageValue = tf.read_file(image_filename)
    labelValue = tf.read_file(label_filename)

    image_bytes = tf.image.decode_png(imageValue)
    label_bytes = tf.image.decode_png(labelValue)

    image = tf.reshape(image_bytes, (IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_DEPTH))
    label = tf.reshape(label_bytes, (IMAGE_HEIGHT, IMAGE_WIDTH, 1))

    return image, label
开发者ID:mengli,项目名称:PcmAudioRecorder,代码行数:14,代码来源:kitti_segnet.py


示例6: main

def main(_):
    path_to_image_file = FLAGS.image
    path_to_restore_checkpoint_file = FLAGS.restore_checkpoint

    image = tf.image.decode_jpeg(tf.read_file(path_to_image_file), channels=3)
    image = tf.reshape(image, [64, 64, 3])
    image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    image = tf.multiply(tf.subtract(image, 0.5), 2)
    image = tf.image.resize_images(image, [54, 54])
    images = tf.reshape(image, [1, 54, 54, 3])

    length_logits, digits_logits = Model.inference(images, drop_rate=0.0)
    length_predictions = tf.argmax(length_logits, axis=1)
    digits_predictions = tf.argmax(digits_logits, axis=2)
    digits_predictions_string = tf.reduce_join(tf.as_string(digits_predictions), axis=1)

    with tf.Session() as sess:
        restorer = tf.train.Saver()
        restorer.restore(sess, path_to_restore_checkpoint_file)

        length_predictions_val, digits_predictions_string_val = sess.run([length_predictions, digits_predictions_string])
        length_prediction_val = length_predictions_val[0]
        digits_prediction_string_val = digits_predictions_string_val[0]
        print 'length: %d' % length_prediction_val
        print 'digits: %s' % digits_prediction_string_val
开发者ID:Ankita-Das,项目名称:SVHNClassifier,代码行数:25,代码来源:inference.py


示例7: get_batch

def get_batch(image,label,image_W,image_H,batch_size,capacity):
	'''
	Args:
        image: list type
        label: list type
        image_W: image width
        image_H: image height
        batch_size: batch size
        capacity: the maximum elements in queue
    Returns:
        image_batch: 4D tensor [batch_size, width, height, 3], dtype=tf.float32
        label_batch: 1D tensor [batch_size], dtype=tf.int32
    '''

	image = tf.cast(image,tf.string)
	label = tf.cast(label,tf.int32)

	input_queue = tf.train.slice_input_producer([image,label])
	label = input_queue[1]
	image_contents = tf.read_file(input_queue[0])
	image = tf.image.decode_jpeg(image_contents,channels=3)

	image = tf.image.resize_image_with_crop_or_pad(image,image_W,image_H)

	image = tf.image.per_image_standardization(image)

	image_batch,label_batch = tf.train.batch([image,label],
    											batch_size = batch_size,
    											num_threads = 64,
    											capacity = capacity)

	label_batch = tf.reshape(label_batch,[batch_size])
	image_batch = tf.cast(image_batch,tf.float32)

	return image_batch,label_batch
开发者ID:zhuzhuxia1994,项目名称:CK-TensorFlow,代码行数:35,代码来源:input_data.py


示例8: read_tensor_from_image_file

    def read_tensor_from_image_file(self, file_name, input_height=299, input_width=299, input_mean=0, input_std=255):
        input_name = "file_reader"
        output_name = "normalized"

        file_reader = tf.read_file(file_name, input_name)

        if file_name.endswith(".png"):
            image_reader = tf.image.decode_png(file_reader, channels=3, name='png_reader')
        elif file_name.endswith(".gif"):
            image_reader = tf.squeeze(tf.image.decode_gif(file_reader, name='gif_reader'))
        elif file_name.endswith(".bmp"):
            image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')
        else:
            image_reader = tf.image.decode_jpeg(file_reader, channels=3, name='jpeg_reader')

        float_caster = tf.cast(image_reader, tf.float32)
        dims_expander = tf.expand_dims(float_caster, 0);
        resized = tf.image.resize_bilinear(dims_expander, [self.input_height, self.input_width])
        normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
        sess = tf.Session()

        result = sess.run(normalized)
        sess.close()

        return result
开发者ID:CoderBotOrg,项目名称:coderbot,代码行数:25,代码来源:cnn_classifier.py


示例9: read_jpeg

def read_jpeg(filename):
    value = tf.read_file(filename)
    decoded_image = tf.image.decode_jpeg(value, channels=FLAGS.depth)
    resized_image = tf.image.resize_images(decoded_image, FLAGS.raw_height, FLAGS.raw_width)
    resized_image = tf.cast(resized_image, tf.uint8)

    return resized_image
开发者ID:thomaspark-pkj,项目名称:tf-image-classification,代码行数:7,代码来源:convert.py


示例10: preprocess_image

def preprocess_image(file_name, output_height=224, output_width=224,
                     num_channels=3):
  """Run standard ImageNet preprocessing on the passed image file.

  Args:
    file_name: string, path to file containing a JPEG image
    output_height: int, final height of image
    output_width: int, final width of image
    num_channels: int, depth of input image

  Returns:
    Float array representing processed image with shape
      [output_height, output_width, num_channels]

  Raises:
    ValueError: if image is not a JPEG.
  """
  if imghdr.what(file_name) != "jpeg":
    raise ValueError("At this time, only JPEG images are supported. "
                     "Please try another image.")

  image_buffer = tf.read_file(file_name)
  normalized = imagenet_preprocessing.preprocess_image(
      image_buffer=image_buffer,
      bbox=None,
      output_height=output_height,
      output_width=output_width,
      num_channels=num_channels,
      is_training=False)

  with tf.Session(config=get_gpu_config()) as sess:
    result = sess.run([normalized])

  return result[0]
开发者ID:snurkabill,项目名称:models,代码行数:34,代码来源:tensorrt.py


示例11: get_input

def get_input(input_file, batch_size, im_size=224):
    input = DATA_DIR + 'SegNet/SiftFlow/' + input_file
    filenames = []
    with open(input, 'r') as f:
    	for line in f:
	        filenames.append('{}/{}'.format(
	        					DATA_DIR, line.strip()))
    # filenames.append('{}/{}.jpg {}'.format(
    #     DATA_DIR, line.strip(),
    #     line.strip()))

    filename_queue = tf.train.string_input_producer(filenames)
    filename, label_dir = tf.decode_csv(filename_queue.dequeue(), [[""], [""]], " ")

    label = label_dir;

    file_contents = tf.read_file(filename)
    im = tf.image.decode_jpeg(file_contents)
    im = tf.image.resize_images(im, im_size, im_size, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
    im = tf.reshape(im, [im_size, im_size, 3])
    im = tf.to_float(im)
    im_mean = tf.constant([122.67892, 116.66877, 104.00699], dtype=tf.float32)
    im = tf.sub(im, im_mean)
    # im = tf.image.per_image_whitening(im)
    # im = tf.image.per_image_whitening(im)
    min_queue_examples = int(10000 * 0.4)
    example_batch, lbl_batch = tf.train.batch([im, label],
                                            num_threads=1,
                                            batch_size=batch_size,
                                            capacity=min_queue_examples + 3 * batch_size)
    return example_batch, lbl_batch
开发者ID:hananico,项目名称:SemiSeg,代码行数:31,代码来源:read_data.py


示例12: _read_image_and_label

    def _read_image_and_label(self, image_file, label):
        image = tf.read_file(image_file)
        image = tf.image.decode_jpeg(image)
        image = tf.image.resize_images(image, [224, 224])
        image = tf.reshape(image, (1, 224, 224, 3))  # for resnet50

        return image, label
开发者ID:bcho,项目名称:homework,代码行数:7,代码来源:dataset.py


示例13: input_images

 def input_images(self):
     num_images = (self._sqlen + self._args.lookback_length) * self._bsize
     images = tf.map_fn(lambda x: tf.image.decode_jpeg(tf.read_file(x)),
                        tf.reshape(self._imfiles, shape=[num_images]),
                        dtype=tf.uint8)
     images.set_shape([None, ds.HEIGHT, ds.WIDTH, ds.CHANNELS])
     return images
开发者ID:gokhanettin,项目名称:driverless-car,代码行数:7,代码来源:model.py


示例14: build_prepro_graph

def build_prepro_graph(inception_path):
    global input_layer, output_layer
    with open(inception_path, 'rb') as f:
        fileContent = f.read()

    graph_def = tf.GraphDef()
    graph_def.ParseFromString(fileContent)
    tf.import_graph_def(graph_def)
    graph = tf.get_default_graph()

    input_layer = graph.get_tensor_by_name("import/InputImage:0")
    output_layer = graph.get_tensor_by_name(
        "import/InceptionV4/Logits/AvgPool_1a/AvgPool:0")

    input_file = tf.placeholder(dtype=tf.string, name="InputFile")
    image_file = tf.read_file(input_file)
    jpg = tf.image.decode_jpeg(image_file, channels=3)
    png = tf.image.decode_png(image_file, channels=3)
    output_jpg = tf.image.resize_images(jpg, [299, 299]) / 255.0
    output_jpg = tf.reshape(
        output_jpg, [
            1, 299, 299, 3], name="Preprocessed_JPG")
    output_png = tf.image.resize_images(png, [299, 299]) / 255.0
    output_png = tf.reshape(
        output_png, [
            1, 299, 299, 3], name="Preprocessed_PNG")
    return input_file, output_jpg, output_png
开发者ID:suryawanshishantanu6,项目名称:image-caption-generator,代码行数:27,代码来源:convfeatures.py


示例15: convertDataset

def convertDataset(image_dir):

    num_labels = len(LABELS_DICT)
    label = np.eye(num_labels)  # Convert labels to one-hot-vector
    i = 0
    
    session = tf.Session()
    init = tf.initialize_all_variables()
    session.run(init)

    log.info("Start processing images (Dataset.py) ")
    start = timer()
    for dirName in os.listdir(image_dir):
        label_i = label[i]
        print("ONE_HOT_ROW = ", label_i)
        i += 1
        # log.info("Execution time of convLabels function = %.4f sec" % (end1-start1))
        path = os.path.join(image_dir, dirName)
        for img in os.listdir(path):
            img_path = os.path.join(path, img)
            if os.path.isfile(img_path) and (img.endswith('jpeg') or
                                             (img.endswith('jpg'))):
                img_bytes = tf.read_file(img_path)
                img_u8 = tf.image.decode_jpeg(img_bytes, channels=3)
                img_u8_eval = session.run(img_u8)
                image = tf.image.convert_image_dtype(img_u8_eval, tf.float32)
                img_padded_or_cropped = tf.image.resize_image_with_crop_or_pad(image, IMG_SIZE, IMG_SIZE)
                img_padded_or_cropped = tf.reshape(img_padded_or_cropped, shape=[IMG_SIZE * IMG_SIZE, 3])
                yield img_padded_or_cropped.eval(session=session), label_i
    end = timer()
    log.info("End processing images (Dataset.py) - Time = %.2f sec" % (end-start))
开发者ID:daniele-sartiano,项目名称:ConvNet,代码行数:31,代码来源:Dataset.py


示例16: read_one_image

def read_one_image(fname, **kwargs):
    """Reads one image given a filepath

    Parameters
    -----------
    fname : str
        path to a JPEG file
    img_shape : tuple
        (kwarg) shape of the eventual image. Default is (224, 224, 3)
    is_training : bool
        (kwarg) boolean to tell the loader function if the graph is in training
        mode or testing. Default is True

    Returns
    -------
    preprocessed image
    """
    img_shape = kwargs.pop("image_shape", (224, 224, 3))
    is_training = kwargs.pop("is_training", False)
    # read the image file
    content = tf.read_file(fname)

    # decode buffer as jpeg
    img_raw = tf.image.decode_jpeg(content, channels=img_shape[-1])

    return preprocess_image(img_raw, img_shape[0], img_shape[1], is_training=is_training)
开发者ID:Andrew62,项目名称:dogcatcher,代码行数:26,代码来源:datatf.py


示例17: read_image

def read_image(filename, label):
    image_string = tf.read_file(filename)
    image_decoded = tf.image.decode_png(image_string, channels=3)
    image_resized = tf.image.resize_images(image_decoded, [28, 28])
    image_resized = tf.cast(image_resized, tf.float32)
    image_resized = image_resized / 255.0
    return image_resized, label
开发者ID:JieZou1,项目名称:PanelSeg,代码行数:7,代码来源:label_classification_2.py


示例18: read_tensor_from_image_file

def read_tensor_from_image_file(file_name):
  input_name = "file_reader"
  output_name = "normalized"
  width = input_size
  height = input_size
  num_channels = 3
  file_reader = tf.read_file(file_name, input_name)
  if file_name.endswith(".png"):
    image_reader = tf.image.decode_png(file_reader, channels = 3,
                                       name='png_reader')
  elif file_name.endswith(".gif"):
    image_reader = tf.squeeze(tf.image.decode_gif(file_reader,
                                                  name='gif_reader'))
  elif file_name.endswith(".bmp"):
    image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')
  else:
    image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
                                        name='jpeg_reader')
  float_caster = tf.cast(image_reader, tf.float32)
  dims_expander = tf.expand_dims(float_caster, 0);
  # resized = tf.image.resize_bilinear(dims_expander, [input_size, input_size])
  normalized = tf.divide(tf.subtract(dims_expander, [input_mean]), [input_std])
  patches = tf.extract_image_patches(normalized,
       ksizes=[1, patch_height, patch_width, 1],
       strides=[1, patch_height/4, patch_width/4, 1],
       rates=[1,1,1,1],
       padding="VALID")
  patches_shape = tf.shape(patches)
  patches = tf.reshape(patches, [-1, patch_height, patch_width, num_channels])
  patches = tf.image.resize_images(patches, [height, width])
  patches = tf.reshape(patches, [-1, height, width, num_channels])
  sess = tf.Session()
  return sess.run([patches, patches_shape])
开发者ID:jembezmamy,项目名称:away-pigeons,代码行数:33,代码来源:classifier.py


示例19: read

 def read(filename_queue):
   value = filename_queue.dequeue()
   fpath, label = tf.decode_csv(
       value, record_defaults=[[''], ['']],
       field_delim=' ')
   image_buffer = tf.read_file(fpath)
   return [image_buffer, label]
开发者ID:wanjinchang,项目名称:ActionVLAD,代码行数:7,代码来源:places365.py


示例20: image_processing

    def image_processing(self, filename):
        x = tf.read_file(filename)
        x_decode = tf.image.decode_jpeg(x, channels=self.channels)
        img = tf.image.resize_images(x_decode, [self.load_size, self.load_size])
        img = tf.cast(img, tf.float32) / 127.5 - 1

        return img
开发者ID:zlpsls,项目名称:Self-Attention-GAN-Tensorflow,代码行数:7,代码来源:utils.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python tensorflow.real函数代码示例发布时间:2022-05-27
下一篇:
Python tensorflow.rank函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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