def do_predict(image_ids): image_datas = [] for image_id in image_ids: image_test = Image.open('testset/' + image_id.replace('.xml', '.' + cfg.image_format)) resized_image = image_test.resize((cfg.sample_size, cfg.sample_size), Image.BICUBIC) image_data = np.array(resized_image, dtype='float32') image_datas.append((image_id, image_data, image_test)) imgs_holder = tf.placeholder(tf.float32, shape=[1, cfg.sample_size, cfg.sample_size, 3]) istraining = tf.constant(False, tf.bool) cfg.batch_size = 1 cfg.scratch = True model = yolov3(imgs_holder, None, istraining) img_hw = tf.placeholder(dtype=tf.float32, shape=[2]) boxes, scores, classes = model.pedict(img_hw, iou_threshold=0.5, score_threshold=0.001) saver = tf.train.Saver() ckpt_dir = 'ckpt/' with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(ckpt_dir) saver.restore(sess, ckpt.model_checkpoint_path) gs = int(ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]) print('Restore batch: ', gs) for image_id, image_data, image_test in image_datas[:5]: boxes_, scores_, classes_ = sess.run([boxes, scores, classes], feed_dict={ img_hw: [image_test.size[1], image_test.size[0]], imgs_holder: np.reshape(image_data / 255, [1, cfg.sample_size, cfg.sample_size, 3])}) try: draw_xml(np.array(image_test, dtype=np.float32) / 255, boxes_, classes_, cfg.names, scores=scores_, image_id=image_id) print('predict:', image_id) except Exception as e: print(e)
from draw_boxes import draw_boxes import matplotlib.pyplot as plt # IMG_ID ='008957' # image_test = Image.open('/home/raytroop/Dataset4ML/VOC2007/VOCdevkit/VOC2007/JPEGImages/{}.jpg'.format(IMG_ID)) image_test = Image.open('image/dog.jpg') resized_image = image_test.resize((416, 416), Image.BICUBIC) image_data = np.array(resized_image, dtype='float32') imgs_holder = tf.placeholder(tf.float32, shape=[1, 416, 416, 3]) istraining = tf.constant(False, tf.bool) cfg.batch_size = 1 cfg.scratch = True model = yolov3(imgs_holder, None, istraining) img_hw = tf.placeholder(dtype=tf.float32, shape=[2]) boxes, scores, classes = model.pedict(img_hw, iou_threshold=0.5, score_threshold=0.5) saver = tf.train.Saver() ckpt_dir = './ckpt/' with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(ckpt_dir) saver.restore(sess, ckpt.model_checkpoint_path) boxes_, scores_, classes_ = sess.run([boxes, scores, classes], feed_dict={ img_hw: [image_test.size[1], image_test.size[0]], imgs_holder: np.reshape(image_data / 255, [1, 416, 416, 3])}) image_draw = draw_boxes(np.array(image_test, dtype=np.float32) / 255, boxes_, classes_, cfg.names, scores=scores_)
from config import cfg from PIL import Image, ImageDraw, ImageFont from draw_boxes import draw_boxes import matplotlib.pyplot as plt # IMG_ID ='008957' # image_test = Image.open('/home/raytroop/Dataset4ML/VOC2007/VOCdevkit/VOC2007/JPEGImages/{}.jpg'.format(IMG_ID)) imgs_holder = tf.placeholder(tf.float32, shape=[1, 416, 416, 3]) istraining = tf.constant(False, tf.bool) cfg.batch_size = 1 cfg.scratch = True model = yolov3(imgs_holder, None, istraining) img_hw = tf.placeholder(dtype=tf.float32, shape=[2]) boxes, scores, classes = model.pedict(img_hw, iou_threshold=0.5, score_threshold=0.5) saver = tf.train.Saver() ckpt_dir = './ckpt/' with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(ckpt_dir) print(ckpt.model_checkpoint_path) saver.restore(sess, ckpt.model_checkpoint_path) import datetime import os path = r"E:\github\darknet_windows\build\darknet\x64\data\voc\VOCdevkit\VOC2007\JPEGImages" files = os.listdir(path) # files.sort(key=lambda x: int(x[:-4]))
def do_predict(image_ids): image_datas = [] for image_id in image_ids[:]: image_test = Image.open(testset + '\\' + image_id) resized_image = image_test.resize((cfg.sample_size, cfg.sample_size), Image.BICUBIC) image_data = np.array(resized_image, dtype='float32') image_datas.append((image_id, image_data, image_test)) imgs_holder = tf.placeholder( tf.float32, shape=[1, cfg.sample_size, cfg.sample_size, 3]) istraining = tf.constant(False, tf.bool) cfg.batch_size = 1 cfg.scratch = True model = yolov3(imgs_holder, None, istraining) img_hw = tf.placeholder(dtype=tf.float32, shape=[2]) boxes, scores, classes = model.pedict(img_hw, iou_threshold=0.5, score_threshold=score_threshold) saver = tf.train.Saver() with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(ckpt_dir) saver.restore(sess, ckpt.model_checkpoint_path) gs = int(ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]) print('Restore batch: ', gs) for image_id, image_data, image_test in image_datas: boxes_, scores_, classes_ = sess.run( [boxes, scores, classes], feed_dict={ img_hw: [image_test.size[1], image_test.size[0]], imgs_holder: np.reshape(image_data / 255, [1, cfg.sample_size, cfg.sample_size, 3]) }) try: image_draw = draw_boxes( np.array(image_test, dtype=np.float32) / 255, boxes_, classes_, cfg.names, scores=scores_) # cv2.imshow("prediction.png", cv2.cvtColor(image_draw, cv2.COLOR_RGB2BGR)) print('predict:', image_id) # tree = draw_xml(np.array(image_test, dtype=np.float32) / 255, boxes_, classes_, cfg.names, scores=scores_, image_id=image_id) # tree.write(result_dir + '\\predicted_xmls\\{}.xml'.format(image_id.split('.')[0])) cv2.imwrite(result_dir + '\\' + image_id, cv2.cvtColor(image_draw, cv2.COLOR_RGB2BGR), [int(cv2.IMWRITE_PNG_COMPRESSION), 9]) # fig = plt.figure(frameon=False) # ax = plt.Axes(fig, [0, 0, 1, 1]) # ax.set_axis_off() # fig.add_axes(ax) # plt.imshow(image_draw, interpolation='none') # plt.savefig('C:\\Users\\P900\\Desktop\\myWork\\YOLOv3_tf\\prediction.jpg', dpi='figure', interpolation='none') # # fig.savefig('prediction.jpg') # plt.show() except Exception as e: print(e)
from yolo_top import yolov3 import numpy as np import tensorflow as tf img = tf.constant(np.random.normal(0, 1, [8, 416, 416, 3]), tf.float32) truth = tf.constant(np.random.randint(0, 2, size=[8, 30, 5]), tf.float32) istraining = tf.constant(False, tf.bool) model = yolov3(img, truth, istraining) loss = model.compute_loss() sess = tf.Session() sess.run(tf.global_variables_initializer()) print(sess.run(loss))
from yolo_top import yolov3 import numpy as np import tensorflow as tf from data_pipeline import data_pipeline import config as cfg import os os.environ["CUDA_VISIBLE_DEVICES"]="3" file_path = 'E:/Python/tensorflow/YOLO/people count/yuncong_data/our/trainval_2014.tfrecord' log_dir='E:/Python/tensorflow/YOLO/people count/yuncong_data/our/log/' imgs, true_boxes = data_pipeline(file_path, cfg.batch_size) istraining = tf.constant(True, tf.bool) model = yolov3(imgs, true_boxes, istraining) with tf.name_scope('loss'): loss,AVG_IOU,coordinates_loss_sum,objectness_loss,no_objects_loss_mean = model.compute_loss() tf.summary.scalar('loss', loss) tf.summary.scalar('avg', AVG_IOU) tf.summary.scalar('coord', coordinates_loss_sum) tf.summary.scalar('obj', objectness_loss) tf.summary.scalar('no_obj', no_objects_loss_mean) global_step = tf.Variable(0, trainable=False) #lr = tf.train.exponential_decay(0.0001, global_step=global_step, decay_steps=2e4, decay_rate=0.1) lr = tf.train.piecewise_constant(global_step, [30000, 45000], [1e-4, 5e-5, 1e-5]) ##作用在不同步长时更改学习率 optimizer = tf.train.AdamOptimizer(learning_rate=lr) #optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.00001) update_op = tf.get_collection(tf.GraphKeys.UPDATE_OPS) vars_det = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="Head") # for var in vars_det: # print(var) with tf.control_dependencies(update_op):
from yolo_top import yolov3 import numpy as np import tensorflow as tf img = tf.constant(np.random.normal(0, 1, [8, 416, 416, 3]), tf.float32) truth = tf.constant(np.random.randint(0, 2, size=[8, 30, 5]), tf.float32) istraining = tf.constant(True, tf.bool) model = yolov3(img, truth, istraining) loss = model.compute_loss() sess = tf.Session() sess.run(tf.global_variables_initializer()) print(sess.run(loss))
# print(img,truth) # tfconfig = tf.ConfigProto() # tfconfig.gpu_options.allow_growth = True # tfconfig.gpu_options.per_process_gpu_memory_fraction = 0.9 img_holder = tf.placeholder(tf.float32, shape=(cfg.batch_size, cfg.train.image_resized, cfg.train.image_resized, 3), name='img_holder') truth_holder = tf.placeholder(tf.float32, shape=(cfg.batch_size, 30, 5), name='truth_holder') istraining = tf.placeholder(tf.bool, shape=(), name='istraining') model = yolov3(img_holder, truth_holder, istraining, trainable_head=True) loss = model.compute_loss() # optimizer global_step = tf.Variable(0, trainable=False) # lr = tf.train.exponential_decay(0.0001, global_step=global_step, decay_steps=2e4, decay_rate=0.1) lr1 = tf.train.piecewise_constant(global_step, [2215 * 3, 2215 * 5], [5e-5, 1e-4, 1e-5]) # lr2 = tf.train.piecewise_constant(global_step, [100, 1000], [1e-5, 5e-6, 1e-6]) # optimizer1 = tf.train.AdamOptimizer(learning_rate=lr1) optimizer2 = tf.train.AdamOptimizer(learning_rate=lr1) # optimizer = tf.train.MomentumOptimizer(learning_rate=lr, momentum=0.9) update_op = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
from yolo_top import yolov3 import numpy as np import tensorflow as tf from data_pipeline import data_pipeline from config import cfg file_path = 'trainval0712.tfrecords' imgs, true_boxes = data_pipeline(file_path, cfg.batch_size) istraining = tf.constant(True, tf.bool) model = yolov3(imgs, true_boxes, istraining) loss = model.compute_loss() global_step = tf.Variable(0, trainable=False) # lr = tf.train.exponential_decay(0.0001, global_step=global_step, decay_steps=2e4, decay_rate=0.1) lr = tf.train.piecewise_constant(global_step, [40000, 45000], [1e-3, 1e-4, 1e-5]) optimizer = tf.train.AdamOptimizer(learning_rate=lr) # optimizer = tf.train.MomentumOptimizer(learning_rate=lr, momentum=0.9) update_op = tf.get_collection(tf.GraphKeys.UPDATE_OPS) vars_det = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="Head") # for var in vars_det: # print(var) with tf.control_dependencies(update_op): train_op = optimizer.minimize(loss, global_step=global_step, var_list=vars_det) saver = tf.train.Saver() ckpt_dir = './ckpt/' gs = 0 batch_per_epoch = 2000 cfg.train.max_batches = int(batch_per_epoch * 10) cfg.train.image_resized = 608