code stringlengths 17 6.64M |
|---|
def _add_loss_summaries(total_loss):
'Add summaries for losses in CIFAR-10 model.\n\n Generates moving average for all losses and associated summaries for\n visualizing the performance of the network.\n\n Args:\n total_loss: Total loss from loss().\n Returns:\n loss_averages_op: op for generating moving... |
def train(total_loss, global_step):
'Train CIFAR-10 model.\n\n Create an optimizer and apply to all trainable variables. Add moving\n average for all trainable variables.\n\n Args:\n total_loss: Total loss from loss().\n global_step: Integer Variable counting the number of training steps\n processed... |
def maybe_download_and_extract():
"Download and extract the tarball from Alex's website."
dest_directory = FLAGS.data_dir
if (not os.path.exists(dest_directory)):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[(- 1)]
filepath = os.path.join(dest_directory, filename)
if (not... |
def read_cifar10(filename_queue):
'Reads and parses examples from CIFAR10 data files.\n\n Recommendation: if you want N-way read parallelism, call this function\n N times. This will give you N independent Readers reading different\n files & positions within those files, which will give better mixing of\n exa... |
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle):
'Construct a queued batch of images and labels.\n\n Args:\n image: 3-D Tensor of [height, width, 3] of type.float32.\n label: 1-D Tensor of type.int32\n min_queue_examples: int32, minimum number of samples to ret... |
def distorted_inputs(data_dir, batch_size):
'Construct distorted input for CIFAR training using the Reader ops.\n\n Args:\n data_dir: Path to the CIFAR-10 data directory.\n batch_size: Number of images per batch.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\... |
def inputs(eval_data, data_dir, batch_size):
'Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n data_dir: Path to the CIFAR-10 data directory.\n batch_size: Number of images per batch.\n\n Returns:\n ima... |
def conv_variable(weight_shape):
w = weight_shape[0]
h = weight_shape[1]
input_channels = weight_shape[2]
output_channels = weight_shape[3]
d = (1.0 / np.sqrt(((input_channels * w) * h)))
bias_shape = [output_channels]
weight = tf.Variable(tf.random_uniform(weight_shape, minval=(- d), maxv... |
def conv2d(x, W, stride):
return tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding='SAME')
|
def maxpool2d(x, k=2):
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
|
def IPE_r1(F1F2, F2F3, F3F4, F4F5, F5F6, x_cor, y_cor, FLAGS):
img_pair = tf.concat([F1F2, F2F3, F3F4, F4F5, F5F6], 0)
(w_1_1, b_1_1) = conv_variable([10, 10, (FLAGS.col_dim * 2), 4])
h_1_1 = tf.nn.relu((conv2d(img_pair, w_1_1, 1) + b_1_1))
(w_1_2, b_1_2) = conv_variable([10, 10, 4, 4])
h_1_2 = tf... |
def IPE_r2(F1F2, F2F3, F3F4, F4F5, F5F6, x_cor, y_cor, FLAGS):
fil_num = FLAGS.fil_num
img_pair = tf.concat([F1F2, F2F3, F3F4, F4F5, F5F6], 0)
h_3_2_x_y = tf.concat([img_pair, x_cor, y_cor], 3)
(w_4_1, b_4_1) = conv_variable([3, 3, 10, fil_num])
h_4_1 = tf.nn.relu((conv2d(h_3_2_x_y, w_4_1, 1) + b_... |
def VE(F1, F2, F3, F4, F5, F6, x_cor, y_cor, FLAGS):
F1F2 = tf.concat([F1, F2], 3)
F2F3 = tf.concat([F2, F3], 3)
F3F4 = tf.concat([F3, F4], 3)
F4F5 = tf.concat([F4, F5], 3)
F5F6 = tf.concat([F5, F6], 3)
(pair1, pair2, pair3, pair4, pair5) = IPE_r2(F1F2, F2F3, F3F4, F4F5, F5F6, x_cor, y_cor, FL... |
def core_r1(S, FLAGS, idx):
fil_num = 64
M = tf.unstack(S, FLAGS.No, 1)
SD_in = tf.reshape(S, [(- 1), FLAGS.Ds])
with tf.variable_scope(('self-dynamics' + str(idx))):
w1 = tf.get_variable('w1', shape=[FLAGS.Ds, fil_num])
b1 = tf.get_variable('b1', shape=[fil_num])
h1 = tf.nn.re... |
def core_r2(S, FLAGS, idx):
fil_num = 64
M = tf.unstack(S, FLAGS.No, 1)
M_self = np.zeros(FLAGS.No, dtype=object)
for i in range(FLAGS.No):
with tf.variable_scope(((('self-dynamics' + str(idx)) + '_') + str((i + 1)))):
w1 = tf.get_variable('w1', shape=[FLAGS.Ds, fil_num])
... |
def DP(S1, S2, S3, S4, FLAGS):
Sc1 = core_r1(S1, FLAGS, 4)
Sc3 = core_r1(S3, FLAGS, 2)
Sc4 = core_r1(S4, FLAGS, 1)
fil_num = 64
S = tf.concat([Sc1, Sc3, Sc4], 2)
S = tf.reshape(S, [(- 1), (FLAGS.Ds * 3)])
with tf.variable_scope('DP'):
w1 = tf.get_variable('w1', shape=[(FLAGS.Ds * 3... |
def SD(output_dp, FLAGS):
input_sd = tf.reshape(output_dp, [(- 1), FLAGS.Ds])
w1 = tf.Variable(tf.truncated_normal([FLAGS.Ds, 4], stddev=0.1), dtype=tf.float32)
b1 = tf.Variable(tf.zeros([4]), dtype=tf.float32)
h1 = (tf.matmul(input_sd, w1) + b1)
h1 = tf.reshape(h1, [(- 1), FLAGS.No, 4])
retur... |
def add_path(path):
if (path not in sys.path):
sys.path.insert(0, path)
|
def update_config(config_file):
exp_config = None
with open(config_file) as f:
exp_config = edict(yaml.load(f, Loader=yaml.SafeLoader))
for (k, v) in exp_config.items():
if (k in config):
if isinstance(v, dict):
if (k == 'TRAIN'):
... |
def _load_general(data, targets, major_axis):
'Load a list of arrays into a list of arrays specified by slices'
for (d_src, d_targets) in zip(data, targets):
if isinstance(d_targets, nd.NDArray):
d_src.copyto(d_targets)
elif isinstance(d_src, (list, tuple)):
for (src, d... |
def _load_data(batch, targets, major_axis):
'Load data into sliced arrays'
_load_general(batch.data, targets, major_axis)
|
def _load_label(batch, targets, major_axis):
'Load label into sliced arrays'
_load_general(batch.label, targets, major_axis)
|
def _merge_multi_context(outputs, major_axis):
'Merge outputs that lives on multiple context into one, so that they look\n like living on one context.\n '
rets = []
for (tensors, axis) in zip(outputs, major_axis):
if (axis >= 0):
rets.append(nd.concatenate(tensors, axis=axis, alw... |
class DataParallelExecutorGroup(object):
"DataParallelExecutorGroup is a group of executors that lives on a group of devices.\n This is a helper class used to implement data parallelization. Each mini-batch will\n be split and run on the devices.\n\n Parameters\n ----------\n symbol : Symbol\n ... |
class Speedometer(object):
def __init__(self, batch_size, frequent=50):
self.batch_size = batch_size
self.frequent = frequent
self.init = False
self.tic = 0
self.last_count = 0
def __call__(self, param):
'Callback to Show speed.'
count = param.nbatch
... |
def do_checkpoint(prefix, means, stds):
def _callback(iter_no, sym, arg, aux):
arg['bbox_pred_weight_test'] = (arg['bbox_pred_weight'].T * mx.nd.array(stds)).T
arg['bbox_pred_bias_test'] = ((arg['bbox_pred_bias'] * mx.nd.array(stds)) + mx.nd.array(means))
mx.model.save_checkpoint(prefix, ... |
def test_rcnn(cfg, dataset, image_set, root_path, dataset_path, ctx, prefix, epoch, vis, ignore_cache, shuffle, has_rpn, proposal, thresh, logger=None, output_path=None, nms_dets=None, is_docker=False):
if (not logger):
assert False, 'require a logger'
datasets = dataset.split(';')
dataset_paths =... |
def train_rcnn(cfg, dataset, image_set, root_path, dataset_path, frequent, kvstore, flip, shuffle, resume, ctx, pretrained, epoch, prefix, begin_epoch, end_epoch, train_shared, lr, lr_step, proposal, logger=None, output_path=None):
mx.random.seed(np.random.randint(10000))
np.random.seed(np.random.randint(1000... |
class BoxAnnotatorOHEMOperator(mx.operator.CustomOp):
def __init__(self, num_classes, num_reg_classes, rm_last, roi_per_img):
super(BoxAnnotatorOHEMOperator, self).__init__()
self._num_classes = num_classes
self._num_reg_classes = num_reg_classes
self._roi_per_img = roi_per_img
... |
@mx.operator.register('BoxAnnotatorOHEM')
class BoxAnnotatorOHEMProp(mx.operator.CustomOpProp):
def __init__(self, num_classes, num_reg_classes, rm_last, roi_per_img):
super(BoxAnnotatorOHEMProp, self).__init__(need_top_grad=False)
self._num_classes = int(num_classes)
self._num_reg_classe... |
class resnet_v1_101_fpn_dcn_rcnn(Symbol):
def __init__(self):
'\n Use __init__ to define parameter network needs\n '
self.shared_param_list = ['offset_p2', 'offset_p3', 'offset_p4', 'offset_p5', 'rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred']
self.shared_param_dict = {}
... |
class resnet_v1_101_fpn_dcn_rcnn_oneshot_v3(Symbol):
def __init__(self):
'\n Use __init__ to define parameter network needs\n '
self.shared_param_list = ['offset_p2', 'offset_p3', 'offset_p4', 'offset_p5', 'rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred']
self.shared_param_dict ... |
class resnet_v1_101_fpn_dcn_rcnn_rep_noemb(Symbol):
def __init__(self):
'\n Use __init__ to define parameter network needs\n '
self.shared_param_list = ['offset_p2', 'offset_p3', 'offset_p4', 'offset_p5', 'rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred']
self.shared_param_dict =... |
class resnet_v1_101_fpn_rcnn(Symbol):
def __init__(self):
'\n Use __init__ to define parameter network needs\n '
self.shared_param_list = ['rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred']
self.shared_param_dict = {}
for name in self.shared_param_list:
self.s... |
def customize_compiler_for_nvcc(self):
"inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on it.... |
class custom_build_ext(build_ext):
def build_extensions(self):
customize_compiler_for_nvcc(self.compiler)
build_ext.build_extensions(self)
|
def find_in_path(name, path):
'Find a file in a search path'
for dir in path.split(os.pathsep):
binpath = pjoin(dir, name)
if os.path.exists(binpath):
return os.path.abspath(binpath)
return None
|
def locate_cuda():
"Locate the CUDA environment on the system\n Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'\n and values giving the absolute path to each directory.\n Starts by looking for the CUDAHOME env variable. If not found, everything\n is based on finding 'nvcc' in the PATH.... |
def customize_compiler_for_nvcc(self):
"inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on it.... |
class custom_build_ext(build_ext):
def build_extensions(self):
customize_compiler_for_nvcc(self.compiler)
build_ext.build_extensions(self)
|
def find_in_path(name, path):
'Find a file in a search path'
for dir in path.split(os.pathsep):
binpath = pjoin(dir, name)
if os.path.exists(binpath):
return os.path.abspath(binpath)
return None
|
def locate_cuda():
"Locate the CUDA environment on the system\n\n Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'\n and values giving the absolute path to each directory.\n\n Starts by looking for the CUDAHOME env variable. If not found, everything\n is based on finding 'nvcc' in the P... |
def customize_compiler_for_nvcc(self):
"inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on i... |
class custom_build_ext(build_ext):
def build_extensions(self):
customize_compiler_for_nvcc(self.compiler)
build_ext.build_extensions(self)
|
class CUDA_build_ext(build_ext):
'\n Custom build_ext command that compiles CUDA files.\n Note that all extension source files will be processed with this compiler.\n '
def build_extensions(self):
self.compiler.src_extensions.append('.cu')
self.compiler.set_executable('compiler_so', ... |
def get_segmentation_test_batch(segdb, config):
"\n return a dict of train batch\n :param segdb: ['image', 'flipped']\n :param config: the config setting\n :return: data, label, im_info\n "
(imgs, seg_cls_gts, segdb) = get_segmentation_image(segdb, config)
im_array = imgs
im_info = [np.... |
def get_segmentation_train_batch(segdb, config):
"\n return a dict of train batch\n :param segdb: ['image', 'flipped']\n :param config: the config setting\n :return: data, label, im_info\n "
assert (len(segdb) == 1), 'Single batch only'
(imgs, seg_cls_gts, segdb) = get_segmentation_image(se... |
def file_lines_to_list(path):
with open(path) as f:
content = f.readlines()
content = [x.strip() for x in content]
return content
|
class Pred():
def __init__(self, id, conf, left, top, right, bottom):
self.id = id
self.conf = conf
self.left = left
self.top = top
self.right = right
self.bottom = bottom
def calc_pred_intersection(self, pred):
if (not (self.id == pred.id)):
... |
def plot_preds(img, preds, clr=(255, 0, 255)):
if isinstance(img, str):
img = cv2.imread(img)
for pred in preds:
cv2.rectangle(img, (pred.left, pred.top), (pred.right, pred.bottom), clr)
cv2.putText(img, pred.id, (pred.left, pred.top), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, c... |
def read_predictions(txt_file):
lines_list = file_lines_to_list(txt_file)
prediction = []
for line in lines_list:
(id, conf, left, top, right, bottom) = line.split(';')
pred = Pred(id, float(conf), int(left), int(top), int(right), int(bottom))
prediction.append(pred)
return pre... |
class ObjDetStats():
def __init__(self, gt_roidb_fname, cat_ords, logger):
with open(gt_roidb_fname, 'rb') as fid:
self.roidb = cPickle.load(fid)
self.roidb_ni = {}
for entry in self.roidb:
image_path = entry['image']
(im_path, im_name) = os.path.split(... |
class PrefetchingIter(mx.io.DataIter):
'Base class for prefetching iterators. Takes one or more DataIters (\n or any class with "reset" and "next" methods) and combine them with\n prefetching. For example:\n\n Parameters\n ----------\n iters : DataIter or list of DataIter\n one or more DataI... |
def combine_model(prefix1, epoch1, prefix2, epoch2, prefix_out, epoch_out):
(args1, auxs1) = load_checkpoint(prefix1, epoch1)
(args2, auxs2) = load_checkpoint(prefix2, epoch2)
arg_names = (args1.keys() + args2.keys())
aux_names = (auxs1.keys() + auxs2.keys())
args = dict()
for arg in arg_names... |
@mx.init.register
class MyConstant(mx.init.Initializer):
def __init__(self, value):
super(MyConstant, self).__init__(value=value)
self.value = value
def _init_weight(self, _, arr):
arr[:] = mx.nd.array(self.value)
|
def create_logger(root_output_path, cfg, image_set):
if (not os.path.exists(root_output_path)):
os.makedirs(root_output_path)
assert os.path.exists(root_output_path), '{} does not exist'.format(root_output_path)
cfg_name = os.path.basename(cfg).split('.')[0]
config_output_path = os.path.join(r... |
class UnknownImageFormat(Exception):
pass
|
class Image(collections.namedtuple('Image', image_fields)):
def to_str_row(self):
return ('%d\t%d\t%d\t%s\t%s' % (self.width, self.height, self.file_size, self.type, self.path.replace('\t', '\\t')))
def to_str_row_verbose(self):
return ('%d\t%d\t%d\t%s\t%s\t##%s' % (self.width, self.height, ... |
def get_image_size(file_path):
'\n Return (width, height) for a given img file content - no external\n dependencies except the os and struct builtin modules\n '
img = get_image_metadata(file_path)
return (img.width, img.height)
|
def get_image_size_from_bytesio(input, size):
'\n Return (width, height) for a given img file content - no external\n dependencies except the os and struct builtin modules\n\n Args:\n input (io.IOBase): io object support read & seek\n size (int): size of buffer in byte\n '
img = get_... |
def get_image_metadata(file_path):
'\n Return an `Image` object for a given img file content - no external\n dependencies except the os and struct builtin modules\n\n Args:\n file_path (str): path to an image file\n\n Returns:\n Image: (path, type, file_size, width, height)\n '
si... |
def get_image_metadata_from_bytesio(input, size, file_path=None):
'\n Return an `Image` object for a given img file content - no external\n dependencies except the os and struct builtin modules\n\n Args:\n input (io.IOBase): io object support read & seek\n size (int): size of buffer in byte... |
class Test_get_image_size(unittest.TestCase):
data = [{'path': 'lookmanodeps.png', 'width': 251, 'height': 208, 'file_size': 22228, 'type': 'PNG'}]
def setUp(self):
pass
def test_get_image_size_from_bytesio(self):
img = self.data[0]
p = img['path']
with io.open(p, 'rb') a... |
def main(argv=None):
'\n Print image metadata fields for the given file path.\n\n Keyword Arguments:\n argv (list): commandline arguments (e.g. sys.argv[1:])\n Returns:\n int: zero for OK\n '
import logging
import optparse
import sys
prs = optparse.OptionParser(usage='%pr... |
def load_checkpoint(prefix, epoch):
"\n Load model checkpoint from file.\n :param prefix: Prefix of model name.\n :param epoch: Epoch number of model we would like to load.\n :return: (arg_params, aux_params)\n arg_params : dict of str to NDArray\n Model parameter, dict of name to NDArray of... |
def convert_context(params, ctx):
'\n :param params: dict of str to NDArray\n :param ctx: the context to convert to\n :return: dict of str of NDArray with context ctx\n '
new_params = dict()
for (k, v) in params.items():
new_params[k] = v.as_in_context(ctx)
return new_params
|
def load_param(prefix, epoch, convert=False, ctx=None, process=False):
'\n wrapper for load checkpoint\n :param prefix: Prefix of model name.\n :param epoch: Epoch number of model we would like to load.\n :param convert: reference model should be converted to GPU NDArray first\n :param ctx: if conv... |
class WarmupMultiFactorScheduler(LRScheduler):
'Reduce learning rate in factor at steps specified in a list\n\n Assume the weight has been updated by n times, then the learning rate will\n be\n\n base_lr * factor^(sum((step/n)<=1)) # step is an array\n\n Parameters\n ----------\n step: list of i... |
def save_checkpoint(prefix, epoch, arg_params, aux_params):
"Checkpoint the model data into file.\n :param prefix: Prefix of model name.\n :param epoch: The epoch number of the model.\n :param arg_params: dict of str to NDArray\n Model parameter, dict of name to NDArray of net's weights.\n :par... |
class Symbol():
def __init__(self):
self.arg_shape_dict = None
self.out_shape_dict = None
self.aux_shape_dict = None
self.sym = None
@property
def symbol(self):
return self.sym
def get_symbol(self, cfg, is_train=True):
'\n return a generated sy... |
def tic():
import time
global startTime_for_tictoc
startTime_for_tictoc = time.time()
return startTime_for_tictoc
|
def toc():
if ('startTime_for_tictoc' in globals()):
endTime = time.time()
return (endTime - startTime_for_tictoc)
else:
return None
|
def get_dets_class_names(dets_n):
for det in dets_n:
class_names = []
for prd in det[3]:
if (prd in prd2ename.keys()):
class_names += [prd2ename[prd]]
else:
class_names += [prd]
det += [class_names]
return dets_n
|
def print_typical_tray_multiview():
imgname_left = os.path.join(data_root, '15849_left.jpg')
imgname_top = os.path.join(data_root, '15849_top.jpg')
imgname_right = os.path.join(data_root, '15849_right.jpg')
img_left = mpimg.imread(imgname_left)
img_top = mpimg.imread(imgname_top)
img_right = m... |
def display_few_shot_examples():
image_set = ['5cadb37d4b967f67d3047964.jpg', '12686073-1-white.jpg', 'lacoste-logo-sweatshirt-white-p12654-72879_image.jpg']
fig = plt.figure(2)
ff = 2
fig.set_size_inches(((ff * 8.5), ((3 * ff) * 11)), forward=False)
for (cnt, img_basename) in enumerate(image_set)... |
def test_on_query_image(fs_serv, test_img_fname, det_engines):
img = cv2.imread(test_img_fname, (cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION))
score_thresh = 0.1
dets_n = fs_serv.detect_on_image(img, score_thresh=score_thresh, det_engines=det_engines)
dets_n = get_dets_class_names(dets_n)
tes... |
def get_box_proposal(fs_serv, img_path):
from show_boxes import show_detsB_boxes
q_dets_p = fs_serv.get_box_proposal(img_path)
image_basename = os.path.basename(img_path)
save_file_path = os.path.join(disp_folder, 'box_prop_{0}'.format(image_basename))
img = cv2.cvtColor(cv2.imread(img_path, (cv2.... |
def disp_dets2(img, dets, save_file_path):
import matplotlib.pyplot as plt
fig = plt.figure(1)
fig.set_size_inches(((1.4 * 8.5), (1.4 * 11)), forward=False)
plt.axis('off')
img_d = cv2.cvtColor(copy.deepcopy(img), cv2.COLOR_BGR2RGB)
w = 12
for det in dets:
bbox = det[0]
sco... |
def test_on_query_image(fs_serv, test_img_fname, score_thresh=0.1, det_engines=1, figure_factor=2.2, FontScale=2.3):
img = cv2.imread(test_img_fname, (cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION))
dets_n = fs_serv.detect_on_image(img, score_thresh=score_thresh, det_engines=det_engines)
test_img_basen... |
def display_RedHat_examples():
image_set = ['logo1.jpg', 'logo2.jpg', 'logo3.jpg']
fig = plt.figure(2)
ff = 2
fig.set_size_inches(((ff * 8.5), ((3 * ff) * 11)), forward=False)
enrollment_root = '../data/Logo/logo_usecase_data/RedHat/RedHat_enrollment'
for (cnt, img_basename) in enumerate(image... |
def display_lacoste_examples():
image_set = ['5cadb37d4b967f67d3047964.jpg', 'lacoste-logo-sweatshirt-white-p12654-72879_image.jpg', '12686073-1-white.jpg']
fig = plt.figure(2)
ff = 2
fig.set_size_inches(((ff * 8.5), ((3 * ff) * 11)), forward=False)
enrollment_root = '../data/Logo/logo_usecase_dat... |
def display_few_shot_examples():
data_root = '/dccstor/jsdata1/dev/RepMet/notebooks/food_usecase_data'
image_set = ['PRDS990000000000000025_0_192_501_589_885_top.jpg', 'PRDS990000000000000024_0_119_137_523_447_top.jpg', 'PRDS990000000000000023_0_118_208_470_612_top.jpg', 'PRDS990000000000000021_0_571_234_923_... |
def print_typical_tray_multiview():
imgname_left = os.path.join(data_root, '1007_10000000006530_left.jpg')
imgname_top = os.path.join(data_root, '1007_10000000006530_top.jpg')
imgname_right = os.path.join(data_root, '1007_10000000006530_right.jpg')
img_left = mpimg.imread(imgname_left)
img_top = m... |
def disp_dets(img, dets, save_file_path):
import matplotlib.pyplot as plt
fig = plt.figure(1)
ff = 2
fig.set_size_inches(((ff * 8.5), (ff * 11)), forward=False)
plt.axis('off')
img_d = cv2.cvtColor(copy.deepcopy(img), cv2.COLOR_BGR2RGB)
for det in dets:
bbox = det[0]
scores... |
def test_on_query_image(fs_serv, test_img_fname, det_engines):
prd2ename_fname = '/dccstor/jsdata1/dev/RepMet/data/JES_pilot/all_GT.csv_converted_Feb24_prd2ename.csv'
prd2ename_data = np.load(prd2ename_fname)
prd2ename = prd2ename_data['prd2ename']
img = cv2.imread(test_img_fname, (cv2.IMREAD_COLOR | ... |
def get_box_proposal(fs_serv, img_path):
from show_boxes import show_detsB_boxes
output_folder = '../notebooks/food_usecase_data'
q_dets_p = fs_serv.get_box_proposal(img_path)
image_basename = os.path.basename(img_path)
save_file_path = os.path.join(output_folder, 'box_prop_{0}'.format(image_basen... |
def display_few_shot_examples():
data_root = '/opt/DNN/dataset/retail/retail_test'
image_set = ['0de3ec888566edc2.jpg', '2e90529bcb43f44c.jpg', '15a8f82801fe4911.jpg', '34caf4cf9ae0ae92.jpg']
nrows = 1
ncols = np.ceil((len(image_set) / nrows))
print('nrows={0},ncols={1}'.format(nrows, ncols))
... |
def print_typical_tray_multiview():
data_root = '/opt/DNN/dataset/retail/retail_test'
imgname_left = os.path.join(data_root, '0de3ec888566edc2.jpg')
imgname_top = os.path.join(data_root, '2e90529bcb43f44c.jpg')
imgname_right = os.path.join(data_root, '15a8f82801fe4911.jpg')
img_left = mpimg.imread... |
def oid2coco():
img_dir = '/opt/DNN/dataset/openimage/openimage_train'
boxes_csv = '/opt/DNN/dataset/openimage/retail.csv'
json_file = '/opt/DNN/dataset/openimage/annotations/instances_openimage_train.json'
classes_csv = '/opt/DNN/linkdata/eval_dataset/open_images/metadata/class-descriptions-boxable.c... |
def show_detsB_boxes(im, dets_B, scale=1.0, save_file_path='temp.png'):
fig = plt.figure(1)
ff = 1.0
fig.set_size_inches(((ff * 8.5), (ff * 11)), forward=False)
plt.cla()
plt.axis('off')
plt.imshow(im)
for det in dets_B:
det_row = det[0]
cat_name = det[2]
bbox = (de... |
def display_few_shot_test(benchmark, query_image):
import shutil
from FSD_engine import FSD_RepMet as DetectionEngine
from config.bench_config import bcfg, update_bench_config
import cv2
update_bench_config('../experiments/bench_configs/openimage_3_5_10_1.yaml')
(q_dets_B, q_dets_multi_B) = be... |
class Data():
def __init__(self, args):
kwargs = {}
if (not args.cpu):
kwargs['collate_fn'] = default_collate
kwargs['pin_memory'] = True
else:
kwargs['collate_fn'] = default_collate
kwargs['pin_memory'] = False
self.loader_train = N... |
class Benchmark(srdata.SRData):
def __init__(self, args, train=True):
super(Benchmark, self).__init__(args, train, benchmark=True)
def _scan(self):
list_hr = []
list_lr = [[] for _ in self.scale]
for entry in os.scandir(self.dir_hr):
filename = os.path.splitext(en... |
class Demo(data.Dataset):
def __init__(self, args, train=False):
self.args = args
self.name = 'Demo'
self.scale = args.scale
self.idx_scale = 0
self.train = False
self.benchmark = False
self.filelist = []
for f in os.listdir(args.dir_demo):
... |
class DIV2K(srdata.SRData):
def __init__(self, args, train=True):
super(DIV2K, self).__init__(args, train)
self.repeat = (args.test_every // (args.n_train // args.batch_size))
def _scan(self):
list_hr = []
list_lr = [[] for _ in self.scale]
if self.train:
... |
def _ms_loop(dataset, index_queue, data_queue, collate_fn, scale, seed, init_fn, worker_id):
global _use_shared_memory
_use_shared_memory = True
_set_worker_signal_handlers()
torch.set_num_threads(1)
torch.manual_seed(seed)
while True:
r = index_queue.get()
if (r is None):
... |
class _MSDataLoaderIter(_DataLoaderIter):
def __init__(self, loader):
self.dataset = loader.dataset
self.scale = loader.scale
self.collate_fn = loader.collate_fn
self.batch_sampler = loader.batch_sampler
self.num_workers = loader.num_workers
self.pin_memory = (load... |
class MSDataLoader(DataLoader):
def __init__(self, args, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, collate_fn=default_collate, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None):
super(MSDataLoader, self).__init__(dataset, batch_size=batch_size, shuffle=shuff... |
class Adversarial(nn.Module):
def __init__(self, args, gan_type):
super(Adversarial, self).__init__()
self.gan_type = gan_type
self.gan_k = args.gan_k
self.discriminator = discriminator.Discriminator(args, gan_type)
if (gan_type != 'WGAN_GP'):
self.optimizer = ... |
class Discriminator(nn.Module):
def __init__(self, args, gan_type='GAN'):
super(Discriminator, self).__init__()
in_channels = 3
out_channels = 64
depth = 7
bn = True
act = nn.LeakyReLU(negative_slope=0.2, inplace=True)
m_features = [common.BasicBlock(args.n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.