吴裕雄 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]  + "\n"
        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)

原文地址:https://www.cnblogs.com/tszr/p/10358651.html

时间: 2024-11-06 09:39:51

吴裕雄 python深度学习与实践(12)的相关文章

吴裕雄 python深度学习与实践(6)

from pylab import * import pandas as pd import matplotlib.pyplot as plot import numpy as np filePath = ("G:\\MyLearning\\TensorFlow_deep_learn\\data\\dataTest.csv") dataFile = pd.read_csv(filePath,header=None, prefix="V") summary = dat

吴裕雄 python深度学习与实践(1)

#coding = utf8 import threading,time count = 0 class MyThread(threading.Thread): def __init__(self,threadName): super(MyThread,self).__init__(name = threadName) def run(self): global count for i in range(100): count = count + 1 time.sleep(0.3) print(

吴裕雄 python深度学习与实践(2)

#coding = utf8 import threading,time,random count = 0 class MyThread (threading.Thread): def __init__(self,lock,threadName): super(MyThread,self).__init__(name = threadName) self.lock = lock def run(self): global count self.lock.acquire() for i in ra

吴裕雄 python深度学习与实践(3)

import threading, time def doWaiting(): print('start waiting:', time.strftime('%S')) time.sleep(3) print('stop waiting', time.strftime('%S')) thread1 = threading.Thread(target = doWaiting) thread1.start() time.sleep(1) #确保线程thread1已经启动 print('start j

吴裕雄 python深度学习与实践(4)

import numpy,math def softmax(inMatrix): m,n = numpy.shape(inMatrix) outMatrix = numpy.mat(numpy.zeros((m,n))) soft_sum = 0 for idx in range(0,n): outMatrix[0,idx] = math.exp(inMatrix[0,idx]) soft_sum += outMatrix[0,idx] for idx in range(0,n): outMat

吴裕雄 python深度学习与实践(5)

import numpy as np data = np.mat([[1,200,105,3,False], [2,165,80,2,False], [3,184.5,120,2,False], [4,116,70.8,1,False], [5,270,150,4,True]]) row = 0 for line in data: row += 1 print(row) print(data.size) import numpy as np data = np.mat([[1,200,105,3

吴裕雄 python深度学习与实践(7)

import cv2 import numpy as np img = np.mat(np.zeros((300,300))) cv2.imshow("test",img) cv2.waitKey(0) import cv2 import numpy as np img = np.mat(np.zeros((300,300),dtype=np.uint8)) cv2.imshow("test",img) cv2.waitKey(0) import cv2 impor

吴裕雄 python深度学习与实践(8)

import cv2 import numpy as np img = cv2.imread("G:\\MyLearning\\TensorFlow_deep_learn\\data\\lena.jpg") img_hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) turn_green_hsv = img_hsv.copy() turn_green_hsv[:,:,0] = (turn_green_hsv[:,:,0] - 30 ) % 180 tur

吴裕雄 python深度学习与实践(10)

import tensorflow as tf input1 = tf.constant(1) print(input1) input2 = tf.Variable(2,tf.int32) print(input2) input2 = input1 sess = tf.Session() print(sess.run(input2)) import tensorflow as tf input1 = tf.placeholder(tf.int32) input2 = tf.placeholder