zoukankan      html  css  js  c++  java
  • 吴裕雄 python深度学习与实践(12)

    import tensorflow as tf
    
    q = tf.FIFOQueue(1000,"float32")
    counter = tf.Variable(0.0)
    add_op = tf.assign_add(counter, tf.constant(1.0))
    enqueueData_op = q.enqueue(counter)
    
    sess = tf.Session()
    qr = tf.train.QueueRunner(q, enqueue_ops=[add_op, enqueueData_op] * 2)
    sess.run(tf.initialize_all_variables())
    enqueue_threads = qr.create_threads(sess, start=True)  
    
    coord = tf.train.Coordinator()  
    enqueue_threads = qr.create_threads(sess, coord = coord,start=True)  
    
    for i in range(0, 10):  
        print(sess.run(q.dequeue()))  
    coord.request_stop()  
    coord.join(enqueue_threads)  

    import os
    
    path = 'F:\lj\aa\VOCdevkit\VOC2012\JPEGImages\'
    filenames=os.listdir(path)
    strText = ""
    
    with open("E:\train_list.csv", "w") as fid:
        for a in range(len(filenames)):
            strText = path+filenames[a]  + "," + filenames[a].split('_')[0]  + "
    "
            fid.write(strText)
    fid.close()
    import cv2
    import tensorflow as tf
    
    image_add_list = []
    image_label_list = []
    with open("E:\train_list.csv") as fid:
        for image in fid.readlines():
            image_add_list.append(image.strip().split(",")[0])
            image_label_list.append(image.strip().split(",")[1])
            
    img=tf.image.convert_image_dtype(tf.image.decode_jpeg(tf.read_file('F:\lj\aa\VOCdevkit\VOC2012\JPEGImages\2007_000250.jpg'),channels=1),dtype=tf.float32)
    print(img)

    import cv2
    import tensorflow as tf
    
    image_add_list = []
    image_label_list = []
    with open("E:\train_list.csv") as fid:
        for image in fid.readlines():
            image_add_list.append(image.strip().split(",")[0])
            image_label_list.append(image.strip().split(",")[1])
    
    def get_image(image_path):
        return tf.image.convert_image_dtype(tf.image.decode_jpeg(tf.read_file(image_path), channels=1),dtype=tf.uint8)
    
    img = tf.image.convert_image_dtype(tf.image.decode_jpeg(tf.read_file('F:\lj\aa\VOCdevkit\VOC2012\JPEGImages\2007_000250.jpg'), channels=1),dtype=tf.float32)
    
    with tf.Session() as sess:
        cv2Img = sess.run(img)
        img2 = cv2.resize(cv2Img, (200,200))
        cv2.imshow('image', img2)
        cv2.waitKey(0)
    import numpy as np
    import tensorflow as tf
    
    a_data = 0.834
    b_data =  [17]
    c_data = np.array([[0,1,2],[3,4,5]])
    c = c_data.astype(np.uint8)
    c_raw = c.tostring()  #转化成字符串
    
    example = tf.train.Example(
            features=tf.train.Features(
                feature={
                    'a': tf.train.Feature(float_list=tf.train.FloatList(value=[a_data])),
                    'b': tf.train.Feature(int64_list=tf.train.Int64List(value=b_data)),
                    'c': tf.train.Feature(bytes_list=tf.train.BytesList(value=[c_raw]))
                }
            )
    )
    import numpy as np
    import tensorflow as tf
    
    writer = tf.python_io.TFRecordWriter("E:\trainArray.tfrecords")
    for _ in range(100):
        randomArray = np.random.random((1,3))
        array_raw = randomArray.tobytes()
        example = tf.train.Example(features=tf.train.Features(feature={
            "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[0])),
            'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[array_raw]))
        }))
        writer.write(example.SerializeToString())
    writer.close()
    import os
    import tensorflow as tf
    from PIL import Image
    
    path = "E:\tupian"
    filenames=os.listdir(path)
    writer = tf.python_io.TFRecordWriter("E:\train.tfrecords")
    
    for name in filenames:
        class_path = path + os.sep + name
        for img_name in os.listdir(class_path):
            img_path = class_path+os.sep+img_name
            img = Image.open(img_path)
            img = img.resize((500,500))
            img_raw = img.tobytes()
            example = tf.train.Example(features=tf.train.Features(feature={
                "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[int(name.split("_")[0])])),
                'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
            }))
            writer.write(example.SerializeToString())
    import cv2
    import tensorflow as tf
    
    filename = "E:\train.tfrecords"
    filename_queue = tf.train.string_input_producer([filename])
    
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)   #返回文件名和文件
    features = tf.parse_single_example(serialized_example,
        features={
            'label': tf.FixedLenFeature([], tf.int64),
            'image' : tf.FixedLenFeature([], tf.string),
        })
    
    img = tf.decode_raw(features['image'], tf.uint8)
    img = tf.reshape(img, [300, 300,3])
    
    img = tf.cast(img, tf.float32) * (1. / 128) - 0.5
    label = tf.cast(features['label'], tf.int32)
    import cv2
    import tensorflow as tf
    
    filename = "E:\train.tfrecords"
    filename_queue = tf.train.string_input_producer([filename])
    
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)   #返回文件名和文件
    features = tf.parse_single_example(serialized_example,
        features={
            'label': tf.FixedLenFeature([], tf.int64),
            'image' : tf.FixedLenFeature([], tf.string),
        })
    
    img = tf.decode_raw(features['image'], tf.uint8)
    img = tf.reshape(img, [300, 300,3])
    
    sess = tf.Session()
    init = tf.initialize_all_variables()
    
    sess.run(init)
    threads = tf.train.start_queue_runners(sess=sess)
    
    img = tf.cast(img, tf.float32) * (1. / 128) - 0.5
    label = tf.cast(features['label'], tf.int32)
    
    print(img)
    # imgcv2 = sess.run(img)
    # cv2.imshow("cool",imgcv2)
    # cv2.waitKey(0)
    import cv2
    import tensorflow as tf
    
    filename = "E:\train.tfrecords"
    
    def read_and_decode(filename):
        filename_queue = tf.train.string_input_producer([filename])
        reader = tf.TFRecordReader()
        _, serialized_example = reader.read(filename_queue)   #返回文件名和文件
        features = tf.parse_single_example(serialized_example,
            features={
                'label': tf.FixedLenFeature([], tf.int64),
                'image' : tf.FixedLenFeature([], tf.string),
            })
    
        img = tf.decode_raw(features['image'], tf.uint8)
        img = tf.reshape(img, [300, 300,3])
    
        img = tf.cast(img, tf.float32) * (1. / 128) - 0.5
        label = tf.cast(features['label'], tf.int32)
        return img,label
    
    img,label = read_and_decode(filename)
    
    img_batch,label_batch = tf.train.shuffle_batch([img,label],batch_size=1,capacity=10,min_after_dequeue=1)
    
    init = tf.initialize_all_variables()
    sess = tf.Session()
    sess.run(init)
    threads = tf.train.start_queue_runners(sess=sess)
    
    for _ in range(10):
        val = sess.run(img_batch)
        label = sess.run(label_batch)
        val.resize((300,300,3))
        cv2.imshow("cool",val)
        cv2.waitKey()
        print(label)
  • 相关阅读:
    WinRAR v5.90中文正式32&64位整合安装版
    WIN10永久激活工具 HWIDGEN
    Adobe2020套装激活工具
    keka 1.1.26-压缩工具
    python文件和目录操作方法大全(含实例)
    如何使公网能够访问本地web服务器?
    网线那根正极那根负极
    HPUX 大文件系统扩容
    LESS详解之函数(四)
    Win7 安装Apache 2.2.4报错:<OS 5>拒绝访问. :Failed to open the WinNT service manager
  • 原文地址:https://www.cnblogs.com/tszr/p/10358651.html
Copyright © 2011-2022 走看看