repo
stringclasses 679
values | path
stringlengths 6
122
| func_name
stringlengths 2
76
| original_string
stringlengths 87
70.9k
| language
stringclasses 1
value | code
stringlengths 87
70.9k
| code_tokens
sequencelengths 20
6.91k
| docstring
stringlengths 1
21.7k
| docstring_tokens
sequencelengths 1
1.6k
| sha
stringclasses 679
values | url
stringlengths 92
213
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
tensorlayer/tensorlayer | tensorlayer/logging/tl_logging.py | log_every_n | def log_every_n(level, msg, n, *args):
"""Log 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: The level at which to log.
msg: The message to be logged.
n: The number of times this should be called before it is logged.
*args: The args to be substituted into the msg.
"""
count = _GetNextLogCountPerToken(_GetFileAndLine())
log_if(level, msg, not (count % n), *args) | python | def log_every_n(level, msg, n, *args):
"""Log 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: The level at which to log.
msg: The message to be logged.
n: The number of times this should be called before it is logged.
*args: The args to be substituted into the msg.
"""
count = _GetNextLogCountPerToken(_GetFileAndLine())
log_if(level, msg, not (count % n), *args) | [
"def",
"log_every_n",
"(",
"level",
",",
"msg",
",",
"n",
",",
"*",
"args",
")",
":",
"count",
"=",
"_GetNextLogCountPerToken",
"(",
"_GetFileAndLine",
"(",
")",
")",
"log_if",
"(",
"level",
",",
"msg",
",",
"not",
"(",
"count",
"%",
"n",
")",
",",
"*",
"args",
")"
] | Log 'msg % args' at level 'level' once per 'n' times.
Logs the 1st call, (N+1)st call, (2N+1)st call, etc.
Not threadsafe.
Args:
level: The level at which to log.
msg: The message to be logged.
n: The number of times this should be called before it is logged.
*args: The args to be substituted into the msg. | [
"Log",
"msg",
"%",
"args",
"at",
"level",
"level",
"once",
"per",
"n",
"times",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L163-L176 | valid |
tensorlayer/tensorlayer | tensorlayer/logging/tl_logging.py | log_if | def log_if(level, msg, condition, *args):
"""Log 'msg % args' at level 'level' only if condition is fulfilled."""
if condition:
vlog(level, msg, *args) | python | def log_if(level, msg, condition, *args):
"""Log 'msg % args' at level 'level' only if condition is fulfilled."""
if condition:
vlog(level, msg, *args) | [
"def",
"log_if",
"(",
"level",
",",
"msg",
",",
"condition",
",",
"*",
"args",
")",
":",
"if",
"condition",
":",
"vlog",
"(",
"level",
",",
"msg",
",",
"*",
"args",
")"
] | Log 'msg % args' at level 'level' only if condition is fulfilled. | [
"Log",
"msg",
"%",
"args",
"at",
"level",
"level",
"only",
"if",
"condition",
"is",
"fulfilled",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L194-L197 | valid |
tensorlayer/tensorlayer | tensorlayer/logging/tl_logging.py | _GetFileAndLine | def _GetFileAndLine():
"""Returns (filename, linenumber) for the stack frame."""
# Use sys._getframe(). This avoids creating a traceback object.
# pylint: disable=protected-access
f = _sys._getframe()
# pylint: enable=protected-access
our_file = f.f_code.co_filename
f = f.f_back
while f:
code = f.f_code
if code.co_filename != our_file:
return (code.co_filename, f.f_lineno)
f = f.f_back
return ('<unknown>', 0) | python | def _GetFileAndLine():
"""Returns (filename, linenumber) for the stack frame."""
# Use sys._getframe(). This avoids creating a traceback object.
# pylint: disable=protected-access
f = _sys._getframe()
# pylint: enable=protected-access
our_file = f.f_code.co_filename
f = f.f_back
while f:
code = f.f_code
if code.co_filename != our_file:
return (code.co_filename, f.f_lineno)
f = f.f_back
return ('<unknown>', 0) | [
"def",
"_GetFileAndLine",
"(",
")",
":",
"# Use sys._getframe(). This avoids creating a traceback object.",
"# pylint: disable=protected-access",
"f",
"=",
"_sys",
".",
"_getframe",
"(",
")",
"# pylint: enable=protected-access",
"our_file",
"=",
"f",
".",
"f_code",
".",
"co_filename",
"f",
"=",
"f",
".",
"f_back",
"while",
"f",
":",
"code",
"=",
"f",
".",
"f_code",
"if",
"code",
".",
"co_filename",
"!=",
"our_file",
":",
"return",
"(",
"code",
".",
"co_filename",
",",
"f",
".",
"f_lineno",
")",
"f",
"=",
"f",
".",
"f_back",
"return",
"(",
"'<unknown>'",
",",
"0",
")"
] | Returns (filename, linenumber) for the stack frame. | [
"Returns",
"(",
"filename",
"linenumber",
")",
"for",
"the",
"stack",
"frame",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L200-L213 | valid |
tensorlayer/tensorlayer | tensorlayer/logging/tl_logging.py | google2_log_prefix | def google2_log_prefix(level, timestamp=None, file_and_line=None):
"""Assemble a logline prefix using the google2 format."""
# pylint: disable=global-variable-not-assigned
global _level_names
# pylint: enable=global-variable-not-assigned
# Record current time
now = timestamp or _time.time()
now_tuple = _time.localtime(now)
now_microsecond = int(1e6 * (now % 1.0))
(filename, line) = file_and_line or _GetFileAndLine()
basename = _os.path.basename(filename)
# Severity string
severity = 'I'
if level in _level_names:
severity = _level_names[level][0]
s = '%c%02d%02d %02d: %02d: %02d.%06d %5d %s: %d] ' % (
severity,
now_tuple[1], # month
now_tuple[2], # day
now_tuple[3], # hour
now_tuple[4], # min
now_tuple[5], # sec
now_microsecond,
_get_thread_id(),
basename,
line
)
return s | python | def google2_log_prefix(level, timestamp=None, file_and_line=None):
"""Assemble a logline prefix using the google2 format."""
# pylint: disable=global-variable-not-assigned
global _level_names
# pylint: enable=global-variable-not-assigned
# Record current time
now = timestamp or _time.time()
now_tuple = _time.localtime(now)
now_microsecond = int(1e6 * (now % 1.0))
(filename, line) = file_and_line or _GetFileAndLine()
basename = _os.path.basename(filename)
# Severity string
severity = 'I'
if level in _level_names:
severity = _level_names[level][0]
s = '%c%02d%02d %02d: %02d: %02d.%06d %5d %s: %d] ' % (
severity,
now_tuple[1], # month
now_tuple[2], # day
now_tuple[3], # hour
now_tuple[4], # min
now_tuple[5], # sec
now_microsecond,
_get_thread_id(),
basename,
line
)
return s | [
"def",
"google2_log_prefix",
"(",
"level",
",",
"timestamp",
"=",
"None",
",",
"file_and_line",
"=",
"None",
")",
":",
"# pylint: disable=global-variable-not-assigned",
"global",
"_level_names",
"# pylint: enable=global-variable-not-assigned",
"# Record current time",
"now",
"=",
"timestamp",
"or",
"_time",
".",
"time",
"(",
")",
"now_tuple",
"=",
"_time",
".",
"localtime",
"(",
"now",
")",
"now_microsecond",
"=",
"int",
"(",
"1e6",
"*",
"(",
"now",
"%",
"1.0",
")",
")",
"(",
"filename",
",",
"line",
")",
"=",
"file_and_line",
"or",
"_GetFileAndLine",
"(",
")",
"basename",
"=",
"_os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"# Severity string",
"severity",
"=",
"'I'",
"if",
"level",
"in",
"_level_names",
":",
"severity",
"=",
"_level_names",
"[",
"level",
"]",
"[",
"0",
"]",
"s",
"=",
"'%c%02d%02d %02d: %02d: %02d.%06d %5d %s: %d] '",
"%",
"(",
"severity",
",",
"now_tuple",
"[",
"1",
"]",
",",
"# month",
"now_tuple",
"[",
"2",
"]",
",",
"# day",
"now_tuple",
"[",
"3",
"]",
",",
"# hour",
"now_tuple",
"[",
"4",
"]",
",",
"# min",
"now_tuple",
"[",
"5",
"]",
",",
"# sec",
"now_microsecond",
",",
"_get_thread_id",
"(",
")",
",",
"basename",
",",
"line",
")",
"return",
"s"
] | Assemble a logline prefix using the google2 format. | [
"Assemble",
"a",
"logline",
"prefix",
"using",
"the",
"google2",
"format",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/logging/tl_logging.py#L216-L248 | valid |
tensorlayer/tensorlayer | tensorlayer/files/dataset_loaders/mpii_dataset.py | load_mpii_pose_dataset | def load_mpii_pose_dataset(path='data', is_16_pos_only=False):
"""Load MPII Human Pose Dataset.
Parameters
-----------
path : str
The path that the data is downloaded to.
is_16_pos_only : boolean
If True, only return the peoples contain 16 pose keypoints. (Usually be used for single person pose estimation)
Returns
----------
img_train_list : list of str
The image directories of training data.
ann_train_list : list of dict
The annotations of training data.
img_test_list : list of str
The image directories of testing data.
ann_test_list : list of dict
The annotations of testing data.
Examples
--------
>>> import pprint
>>> import tensorlayer as tl
>>> img_train_list, ann_train_list, img_test_list, ann_test_list = tl.files.load_mpii_pose_dataset()
>>> image = tl.vis.read_image(img_train_list[0])
>>> tl.vis.draw_mpii_pose_to_image(image, ann_train_list[0], 'image.png')
>>> pprint.pprint(ann_train_list[0])
References
-----------
- `MPII Human Pose Dataset. CVPR 14 <http://human-pose.mpi-inf.mpg.de>`__
- `MPII Human Pose Models. CVPR 16 <http://pose.mpi-inf.mpg.de>`__
- `MPII Human Shape, Poselet Conditioned Pictorial Structures and etc <http://pose.mpi-inf.mpg.de/#related>`__
- `MPII Keyponts and ID <http://human-pose.mpi-inf.mpg.de/#download>`__
"""
path = os.path.join(path, 'mpii_human_pose')
logging.info("Load or Download MPII Human Pose > {}".format(path))
# annotation
url = "http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/"
tar_filename = "mpii_human_pose_v1_u12_2.zip"
extracted_filename = "mpii_human_pose_v1_u12_2"
if folder_exists(os.path.join(path, extracted_filename)) is False:
logging.info("[MPII] (annotation) {} is nonexistent in {}".format(extracted_filename, path))
maybe_download_and_extract(tar_filename, path, url, extract=True)
del_file(os.path.join(path, tar_filename))
# images
url = "http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/"
tar_filename = "mpii_human_pose_v1.tar.gz"
extracted_filename2 = "images"
if folder_exists(os.path.join(path, extracted_filename2)) is False:
logging.info("[MPII] (images) {} is nonexistent in {}".format(extracted_filename, path))
maybe_download_and_extract(tar_filename, path, url, extract=True)
del_file(os.path.join(path, tar_filename))
# parse annotation, format see http://human-pose.mpi-inf.mpg.de/#download
import scipy.io as sio
logging.info("reading annotations from mat file ...")
# mat = sio.loadmat(os.path.join(path, extracted_filename, "mpii_human_pose_v1_u12_1.mat"))
# def fix_wrong_joints(joint): # https://github.com/mitmul/deeppose/blob/master/datasets/mpii_dataset.py
# if '12' in joint and '13' in joint and '2' in joint and '3' in joint:
# if ((joint['12'][0] < joint['13'][0]) and
# (joint['3'][0] < joint['2'][0])):
# joint['2'], joint['3'] = joint['3'], joint['2']
# if ((joint['12'][0] > joint['13'][0]) and
# (joint['3'][0] > joint['2'][0])):
# joint['2'], joint['3'] = joint['3'], joint['2']
# return joint
ann_train_list = []
ann_test_list = []
img_train_list = []
img_test_list = []
def save_joints():
# joint_data_fn = os.path.join(path, 'data.json')
# fp = open(joint_data_fn, 'w')
mat = sio.loadmat(os.path.join(path, extracted_filename, "mpii_human_pose_v1_u12_1.mat"))
for _, (anno, train_flag) in enumerate( # all images
zip(mat['RELEASE']['annolist'][0, 0][0], mat['RELEASE']['img_train'][0, 0][0])):
img_fn = anno['image']['name'][0, 0][0]
train_flag = int(train_flag)
# print(i, img_fn, train_flag) # DEBUG print all images
if train_flag:
img_train_list.append(img_fn)
ann_train_list.append([])
else:
img_test_list.append(img_fn)
ann_test_list.append([])
head_rect = []
if 'x1' in str(anno['annorect'].dtype):
head_rect = zip(
[x1[0, 0] for x1 in anno['annorect']['x1'][0]], [y1[0, 0] for y1 in anno['annorect']['y1'][0]],
[x2[0, 0] for x2 in anno['annorect']['x2'][0]], [y2[0, 0] for y2 in anno['annorect']['y2'][0]]
)
else:
head_rect = [] # TODO
if 'annopoints' in str(anno['annorect'].dtype):
annopoints = anno['annorect']['annopoints'][0]
head_x1s = anno['annorect']['x1'][0]
head_y1s = anno['annorect']['y1'][0]
head_x2s = anno['annorect']['x2'][0]
head_y2s = anno['annorect']['y2'][0]
for annopoint, head_x1, head_y1, head_x2, head_y2 in zip(annopoints, head_x1s, head_y1s, head_x2s,
head_y2s):
# if annopoint != []:
# if len(annopoint) != 0:
if annopoint.size:
head_rect = [
float(head_x1[0, 0]),
float(head_y1[0, 0]),
float(head_x2[0, 0]),
float(head_y2[0, 0])
]
# joint coordinates
annopoint = annopoint['point'][0, 0]
j_id = [str(j_i[0, 0]) for j_i in annopoint['id'][0]]
x = [x[0, 0] for x in annopoint['x'][0]]
y = [y[0, 0] for y in annopoint['y'][0]]
joint_pos = {}
for _j_id, (_x, _y) in zip(j_id, zip(x, y)):
joint_pos[int(_j_id)] = [float(_x), float(_y)]
# joint_pos = fix_wrong_joints(joint_pos)
# visibility list
if 'is_visible' in str(annopoint.dtype):
vis = [v[0] if v.size > 0 else [0] for v in annopoint['is_visible'][0]]
vis = dict([(k, int(v[0])) if len(v) > 0 else v for k, v in zip(j_id, vis)])
else:
vis = None
# if len(joint_pos) == 16:
if ((is_16_pos_only ==True) and (len(joint_pos) == 16)) or (is_16_pos_only == False):
# only use image with 16 key points / or use all
data = {
'filename': img_fn,
'train': train_flag,
'head_rect': head_rect,
'is_visible': vis,
'joint_pos': joint_pos
}
# print(json.dumps(data), file=fp) # py3
if train_flag:
ann_train_list[-1].append(data)
else:
ann_test_list[-1].append(data)
# def write_line(datum, fp):
# joints = sorted([[int(k), v] for k, v in datum['joint_pos'].items()])
# joints = np.array([j for i, j in joints]).flatten()
#
# out = [datum['filename']]
# out.extend(joints)
# out = [str(o) for o in out]
# out = ','.join(out)
#
# print(out, file=fp)
# def split_train_test():
# # fp_test = open('data/mpii/test_joints.csv', 'w')
# fp_test = open(os.path.join(path, 'test_joints.csv'), 'w')
# # fp_train = open('data/mpii/train_joints.csv', 'w')
# fp_train = open(os.path.join(path, 'train_joints.csv'), 'w')
# # all_data = open('data/mpii/data.json').readlines()
# all_data = open(os.path.join(path, 'data.json')).readlines()
# N = len(all_data)
# N_test = int(N * 0.1)
# N_train = N - N_test
#
# print('N:{}'.format(N))
# print('N_train:{}'.format(N_train))
# print('N_test:{}'.format(N_test))
#
# np.random.seed(1701)
# perm = np.random.permutation(N)
# test_indices = perm[:N_test]
# train_indices = perm[N_test:]
#
# print('train_indices:{}'.format(len(train_indices)))
# print('test_indices:{}'.format(len(test_indices)))
#
# for i in train_indices:
# datum = json.loads(all_data[i].strip())
# write_line(datum, fp_train)
#
# for i in test_indices:
# datum = json.loads(all_data[i].strip())
# write_line(datum, fp_test)
save_joints()
# split_train_test() #
## read images dir
logging.info("reading images list ...")
img_dir = os.path.join(path, extracted_filename2)
_img_list = load_file_list(path=os.path.join(path, extracted_filename2), regx='\\.jpg', printable=False)
# ann_list = json.load(open(os.path.join(path, 'data.json')))
for i, im in enumerate(img_train_list):
if im not in _img_list:
print('missing training image {} in {} (remove from img(ann)_train_list)'.format(im, img_dir))
# img_train_list.remove(im)
del img_train_list[i]
del ann_train_list[i]
for i, im in enumerate(img_test_list):
if im not in _img_list:
print('missing testing image {} in {} (remove from img(ann)_test_list)'.format(im, img_dir))
# img_test_list.remove(im)
del img_train_list[i]
del ann_train_list[i]
## check annotation and images
n_train_images = len(img_train_list)
n_test_images = len(img_test_list)
n_images = n_train_images + n_test_images
logging.info("n_images: {} n_train_images: {} n_test_images: {}".format(n_images, n_train_images, n_test_images))
n_train_ann = len(ann_train_list)
n_test_ann = len(ann_test_list)
n_ann = n_train_ann + n_test_ann
logging.info("n_ann: {} n_train_ann: {} n_test_ann: {}".format(n_ann, n_train_ann, n_test_ann))
n_train_people = len(sum(ann_train_list, []))
n_test_people = len(sum(ann_test_list, []))
n_people = n_train_people + n_test_people
logging.info("n_people: {} n_train_people: {} n_test_people: {}".format(n_people, n_train_people, n_test_people))
# add path to all image file name
for i, value in enumerate(img_train_list):
img_train_list[i] = os.path.join(img_dir, value)
for i, value in enumerate(img_test_list):
img_test_list[i] = os.path.join(img_dir, value)
return img_train_list, ann_train_list, img_test_list, ann_test_list | python | def load_mpii_pose_dataset(path='data', is_16_pos_only=False):
"""Load MPII Human Pose Dataset.
Parameters
-----------
path : str
The path that the data is downloaded to.
is_16_pos_only : boolean
If True, only return the peoples contain 16 pose keypoints. (Usually be used for single person pose estimation)
Returns
----------
img_train_list : list of str
The image directories of training data.
ann_train_list : list of dict
The annotations of training data.
img_test_list : list of str
The image directories of testing data.
ann_test_list : list of dict
The annotations of testing data.
Examples
--------
>>> import pprint
>>> import tensorlayer as tl
>>> img_train_list, ann_train_list, img_test_list, ann_test_list = tl.files.load_mpii_pose_dataset()
>>> image = tl.vis.read_image(img_train_list[0])
>>> tl.vis.draw_mpii_pose_to_image(image, ann_train_list[0], 'image.png')
>>> pprint.pprint(ann_train_list[0])
References
-----------
- `MPII Human Pose Dataset. CVPR 14 <http://human-pose.mpi-inf.mpg.de>`__
- `MPII Human Pose Models. CVPR 16 <http://pose.mpi-inf.mpg.de>`__
- `MPII Human Shape, Poselet Conditioned Pictorial Structures and etc <http://pose.mpi-inf.mpg.de/#related>`__
- `MPII Keyponts and ID <http://human-pose.mpi-inf.mpg.de/#download>`__
"""
path = os.path.join(path, 'mpii_human_pose')
logging.info("Load or Download MPII Human Pose > {}".format(path))
# annotation
url = "http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/"
tar_filename = "mpii_human_pose_v1_u12_2.zip"
extracted_filename = "mpii_human_pose_v1_u12_2"
if folder_exists(os.path.join(path, extracted_filename)) is False:
logging.info("[MPII] (annotation) {} is nonexistent in {}".format(extracted_filename, path))
maybe_download_and_extract(tar_filename, path, url, extract=True)
del_file(os.path.join(path, tar_filename))
# images
url = "http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/"
tar_filename = "mpii_human_pose_v1.tar.gz"
extracted_filename2 = "images"
if folder_exists(os.path.join(path, extracted_filename2)) is False:
logging.info("[MPII] (images) {} is nonexistent in {}".format(extracted_filename, path))
maybe_download_and_extract(tar_filename, path, url, extract=True)
del_file(os.path.join(path, tar_filename))
# parse annotation, format see http://human-pose.mpi-inf.mpg.de/#download
import scipy.io as sio
logging.info("reading annotations from mat file ...")
# mat = sio.loadmat(os.path.join(path, extracted_filename, "mpii_human_pose_v1_u12_1.mat"))
# def fix_wrong_joints(joint): # https://github.com/mitmul/deeppose/blob/master/datasets/mpii_dataset.py
# if '12' in joint and '13' in joint and '2' in joint and '3' in joint:
# if ((joint['12'][0] < joint['13'][0]) and
# (joint['3'][0] < joint['2'][0])):
# joint['2'], joint['3'] = joint['3'], joint['2']
# if ((joint['12'][0] > joint['13'][0]) and
# (joint['3'][0] > joint['2'][0])):
# joint['2'], joint['3'] = joint['3'], joint['2']
# return joint
ann_train_list = []
ann_test_list = []
img_train_list = []
img_test_list = []
def save_joints():
# joint_data_fn = os.path.join(path, 'data.json')
# fp = open(joint_data_fn, 'w')
mat = sio.loadmat(os.path.join(path, extracted_filename, "mpii_human_pose_v1_u12_1.mat"))
for _, (anno, train_flag) in enumerate( # all images
zip(mat['RELEASE']['annolist'][0, 0][0], mat['RELEASE']['img_train'][0, 0][0])):
img_fn = anno['image']['name'][0, 0][0]
train_flag = int(train_flag)
# print(i, img_fn, train_flag) # DEBUG print all images
if train_flag:
img_train_list.append(img_fn)
ann_train_list.append([])
else:
img_test_list.append(img_fn)
ann_test_list.append([])
head_rect = []
if 'x1' in str(anno['annorect'].dtype):
head_rect = zip(
[x1[0, 0] for x1 in anno['annorect']['x1'][0]], [y1[0, 0] for y1 in anno['annorect']['y1'][0]],
[x2[0, 0] for x2 in anno['annorect']['x2'][0]], [y2[0, 0] for y2 in anno['annorect']['y2'][0]]
)
else:
head_rect = [] # TODO
if 'annopoints' in str(anno['annorect'].dtype):
annopoints = anno['annorect']['annopoints'][0]
head_x1s = anno['annorect']['x1'][0]
head_y1s = anno['annorect']['y1'][0]
head_x2s = anno['annorect']['x2'][0]
head_y2s = anno['annorect']['y2'][0]
for annopoint, head_x1, head_y1, head_x2, head_y2 in zip(annopoints, head_x1s, head_y1s, head_x2s,
head_y2s):
# if annopoint != []:
# if len(annopoint) != 0:
if annopoint.size:
head_rect = [
float(head_x1[0, 0]),
float(head_y1[0, 0]),
float(head_x2[0, 0]),
float(head_y2[0, 0])
]
# joint coordinates
annopoint = annopoint['point'][0, 0]
j_id = [str(j_i[0, 0]) for j_i in annopoint['id'][0]]
x = [x[0, 0] for x in annopoint['x'][0]]
y = [y[0, 0] for y in annopoint['y'][0]]
joint_pos = {}
for _j_id, (_x, _y) in zip(j_id, zip(x, y)):
joint_pos[int(_j_id)] = [float(_x), float(_y)]
# joint_pos = fix_wrong_joints(joint_pos)
# visibility list
if 'is_visible' in str(annopoint.dtype):
vis = [v[0] if v.size > 0 else [0] for v in annopoint['is_visible'][0]]
vis = dict([(k, int(v[0])) if len(v) > 0 else v for k, v in zip(j_id, vis)])
else:
vis = None
# if len(joint_pos) == 16:
if ((is_16_pos_only ==True) and (len(joint_pos) == 16)) or (is_16_pos_only == False):
# only use image with 16 key points / or use all
data = {
'filename': img_fn,
'train': train_flag,
'head_rect': head_rect,
'is_visible': vis,
'joint_pos': joint_pos
}
# print(json.dumps(data), file=fp) # py3
if train_flag:
ann_train_list[-1].append(data)
else:
ann_test_list[-1].append(data)
# def write_line(datum, fp):
# joints = sorted([[int(k), v] for k, v in datum['joint_pos'].items()])
# joints = np.array([j for i, j in joints]).flatten()
#
# out = [datum['filename']]
# out.extend(joints)
# out = [str(o) for o in out]
# out = ','.join(out)
#
# print(out, file=fp)
# def split_train_test():
# # fp_test = open('data/mpii/test_joints.csv', 'w')
# fp_test = open(os.path.join(path, 'test_joints.csv'), 'w')
# # fp_train = open('data/mpii/train_joints.csv', 'w')
# fp_train = open(os.path.join(path, 'train_joints.csv'), 'w')
# # all_data = open('data/mpii/data.json').readlines()
# all_data = open(os.path.join(path, 'data.json')).readlines()
# N = len(all_data)
# N_test = int(N * 0.1)
# N_train = N - N_test
#
# print('N:{}'.format(N))
# print('N_train:{}'.format(N_train))
# print('N_test:{}'.format(N_test))
#
# np.random.seed(1701)
# perm = np.random.permutation(N)
# test_indices = perm[:N_test]
# train_indices = perm[N_test:]
#
# print('train_indices:{}'.format(len(train_indices)))
# print('test_indices:{}'.format(len(test_indices)))
#
# for i in train_indices:
# datum = json.loads(all_data[i].strip())
# write_line(datum, fp_train)
#
# for i in test_indices:
# datum = json.loads(all_data[i].strip())
# write_line(datum, fp_test)
save_joints()
# split_train_test() #
## read images dir
logging.info("reading images list ...")
img_dir = os.path.join(path, extracted_filename2)
_img_list = load_file_list(path=os.path.join(path, extracted_filename2), regx='\\.jpg', printable=False)
# ann_list = json.load(open(os.path.join(path, 'data.json')))
for i, im in enumerate(img_train_list):
if im not in _img_list:
print('missing training image {} in {} (remove from img(ann)_train_list)'.format(im, img_dir))
# img_train_list.remove(im)
del img_train_list[i]
del ann_train_list[i]
for i, im in enumerate(img_test_list):
if im not in _img_list:
print('missing testing image {} in {} (remove from img(ann)_test_list)'.format(im, img_dir))
# img_test_list.remove(im)
del img_train_list[i]
del ann_train_list[i]
## check annotation and images
n_train_images = len(img_train_list)
n_test_images = len(img_test_list)
n_images = n_train_images + n_test_images
logging.info("n_images: {} n_train_images: {} n_test_images: {}".format(n_images, n_train_images, n_test_images))
n_train_ann = len(ann_train_list)
n_test_ann = len(ann_test_list)
n_ann = n_train_ann + n_test_ann
logging.info("n_ann: {} n_train_ann: {} n_test_ann: {}".format(n_ann, n_train_ann, n_test_ann))
n_train_people = len(sum(ann_train_list, []))
n_test_people = len(sum(ann_test_list, []))
n_people = n_train_people + n_test_people
logging.info("n_people: {} n_train_people: {} n_test_people: {}".format(n_people, n_train_people, n_test_people))
# add path to all image file name
for i, value in enumerate(img_train_list):
img_train_list[i] = os.path.join(img_dir, value)
for i, value in enumerate(img_test_list):
img_test_list[i] = os.path.join(img_dir, value)
return img_train_list, ann_train_list, img_test_list, ann_test_list | [
"def",
"load_mpii_pose_dataset",
"(",
"path",
"=",
"'data'",
",",
"is_16_pos_only",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'mpii_human_pose'",
")",
"logging",
".",
"info",
"(",
"\"Load or Download MPII Human Pose > {}\"",
".",
"format",
"(",
"path",
")",
")",
"# annotation",
"url",
"=",
"\"http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/\"",
"tar_filename",
"=",
"\"mpii_human_pose_v1_u12_2.zip\"",
"extracted_filename",
"=",
"\"mpii_human_pose_v1_u12_2\"",
"if",
"folder_exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"extracted_filename",
")",
")",
"is",
"False",
":",
"logging",
".",
"info",
"(",
"\"[MPII] (annotation) {} is nonexistent in {}\"",
".",
"format",
"(",
"extracted_filename",
",",
"path",
")",
")",
"maybe_download_and_extract",
"(",
"tar_filename",
",",
"path",
",",
"url",
",",
"extract",
"=",
"True",
")",
"del_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"tar_filename",
")",
")",
"# images",
"url",
"=",
"\"http://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/\"",
"tar_filename",
"=",
"\"mpii_human_pose_v1.tar.gz\"",
"extracted_filename2",
"=",
"\"images\"",
"if",
"folder_exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"extracted_filename2",
")",
")",
"is",
"False",
":",
"logging",
".",
"info",
"(",
"\"[MPII] (images) {} is nonexistent in {}\"",
".",
"format",
"(",
"extracted_filename",
",",
"path",
")",
")",
"maybe_download_and_extract",
"(",
"tar_filename",
",",
"path",
",",
"url",
",",
"extract",
"=",
"True",
")",
"del_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"tar_filename",
")",
")",
"# parse annotation, format see http://human-pose.mpi-inf.mpg.de/#download",
"import",
"scipy",
".",
"io",
"as",
"sio",
"logging",
".",
"info",
"(",
"\"reading annotations from mat file ...\"",
")",
"# mat = sio.loadmat(os.path.join(path, extracted_filename, \"mpii_human_pose_v1_u12_1.mat\"))",
"# def fix_wrong_joints(joint): # https://github.com/mitmul/deeppose/blob/master/datasets/mpii_dataset.py",
"# if '12' in joint and '13' in joint and '2' in joint and '3' in joint:",
"# if ((joint['12'][0] < joint['13'][0]) and",
"# (joint['3'][0] < joint['2'][0])):",
"# joint['2'], joint['3'] = joint['3'], joint['2']",
"# if ((joint['12'][0] > joint['13'][0]) and",
"# (joint['3'][0] > joint['2'][0])):",
"# joint['2'], joint['3'] = joint['3'], joint['2']",
"# return joint",
"ann_train_list",
"=",
"[",
"]",
"ann_test_list",
"=",
"[",
"]",
"img_train_list",
"=",
"[",
"]",
"img_test_list",
"=",
"[",
"]",
"def",
"save_joints",
"(",
")",
":",
"# joint_data_fn = os.path.join(path, 'data.json')",
"# fp = open(joint_data_fn, 'w')",
"mat",
"=",
"sio",
".",
"loadmat",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"extracted_filename",
",",
"\"mpii_human_pose_v1_u12_1.mat\"",
")",
")",
"for",
"_",
",",
"(",
"anno",
",",
"train_flag",
")",
"in",
"enumerate",
"(",
"# all images",
"zip",
"(",
"mat",
"[",
"'RELEASE'",
"]",
"[",
"'annolist'",
"]",
"[",
"0",
",",
"0",
"]",
"[",
"0",
"]",
",",
"mat",
"[",
"'RELEASE'",
"]",
"[",
"'img_train'",
"]",
"[",
"0",
",",
"0",
"]",
"[",
"0",
"]",
")",
")",
":",
"img_fn",
"=",
"anno",
"[",
"'image'",
"]",
"[",
"'name'",
"]",
"[",
"0",
",",
"0",
"]",
"[",
"0",
"]",
"train_flag",
"=",
"int",
"(",
"train_flag",
")",
"# print(i, img_fn, train_flag) # DEBUG print all images",
"if",
"train_flag",
":",
"img_train_list",
".",
"append",
"(",
"img_fn",
")",
"ann_train_list",
".",
"append",
"(",
"[",
"]",
")",
"else",
":",
"img_test_list",
".",
"append",
"(",
"img_fn",
")",
"ann_test_list",
".",
"append",
"(",
"[",
"]",
")",
"head_rect",
"=",
"[",
"]",
"if",
"'x1'",
"in",
"str",
"(",
"anno",
"[",
"'annorect'",
"]",
".",
"dtype",
")",
":",
"head_rect",
"=",
"zip",
"(",
"[",
"x1",
"[",
"0",
",",
"0",
"]",
"for",
"x1",
"in",
"anno",
"[",
"'annorect'",
"]",
"[",
"'x1'",
"]",
"[",
"0",
"]",
"]",
",",
"[",
"y1",
"[",
"0",
",",
"0",
"]",
"for",
"y1",
"in",
"anno",
"[",
"'annorect'",
"]",
"[",
"'y1'",
"]",
"[",
"0",
"]",
"]",
",",
"[",
"x2",
"[",
"0",
",",
"0",
"]",
"for",
"x2",
"in",
"anno",
"[",
"'annorect'",
"]",
"[",
"'x2'",
"]",
"[",
"0",
"]",
"]",
",",
"[",
"y2",
"[",
"0",
",",
"0",
"]",
"for",
"y2",
"in",
"anno",
"[",
"'annorect'",
"]",
"[",
"'y2'",
"]",
"[",
"0",
"]",
"]",
")",
"else",
":",
"head_rect",
"=",
"[",
"]",
"# TODO",
"if",
"'annopoints'",
"in",
"str",
"(",
"anno",
"[",
"'annorect'",
"]",
".",
"dtype",
")",
":",
"annopoints",
"=",
"anno",
"[",
"'annorect'",
"]",
"[",
"'annopoints'",
"]",
"[",
"0",
"]",
"head_x1s",
"=",
"anno",
"[",
"'annorect'",
"]",
"[",
"'x1'",
"]",
"[",
"0",
"]",
"head_y1s",
"=",
"anno",
"[",
"'annorect'",
"]",
"[",
"'y1'",
"]",
"[",
"0",
"]",
"head_x2s",
"=",
"anno",
"[",
"'annorect'",
"]",
"[",
"'x2'",
"]",
"[",
"0",
"]",
"head_y2s",
"=",
"anno",
"[",
"'annorect'",
"]",
"[",
"'y2'",
"]",
"[",
"0",
"]",
"for",
"annopoint",
",",
"head_x1",
",",
"head_y1",
",",
"head_x2",
",",
"head_y2",
"in",
"zip",
"(",
"annopoints",
",",
"head_x1s",
",",
"head_y1s",
",",
"head_x2s",
",",
"head_y2s",
")",
":",
"# if annopoint != []:",
"# if len(annopoint) != 0:",
"if",
"annopoint",
".",
"size",
":",
"head_rect",
"=",
"[",
"float",
"(",
"head_x1",
"[",
"0",
",",
"0",
"]",
")",
",",
"float",
"(",
"head_y1",
"[",
"0",
",",
"0",
"]",
")",
",",
"float",
"(",
"head_x2",
"[",
"0",
",",
"0",
"]",
")",
",",
"float",
"(",
"head_y2",
"[",
"0",
",",
"0",
"]",
")",
"]",
"# joint coordinates",
"annopoint",
"=",
"annopoint",
"[",
"'point'",
"]",
"[",
"0",
",",
"0",
"]",
"j_id",
"=",
"[",
"str",
"(",
"j_i",
"[",
"0",
",",
"0",
"]",
")",
"for",
"j_i",
"in",
"annopoint",
"[",
"'id'",
"]",
"[",
"0",
"]",
"]",
"x",
"=",
"[",
"x",
"[",
"0",
",",
"0",
"]",
"for",
"x",
"in",
"annopoint",
"[",
"'x'",
"]",
"[",
"0",
"]",
"]",
"y",
"=",
"[",
"y",
"[",
"0",
",",
"0",
"]",
"for",
"y",
"in",
"annopoint",
"[",
"'y'",
"]",
"[",
"0",
"]",
"]",
"joint_pos",
"=",
"{",
"}",
"for",
"_j_id",
",",
"(",
"_x",
",",
"_y",
")",
"in",
"zip",
"(",
"j_id",
",",
"zip",
"(",
"x",
",",
"y",
")",
")",
":",
"joint_pos",
"[",
"int",
"(",
"_j_id",
")",
"]",
"=",
"[",
"float",
"(",
"_x",
")",
",",
"float",
"(",
"_y",
")",
"]",
"# joint_pos = fix_wrong_joints(joint_pos)",
"# visibility list",
"if",
"'is_visible'",
"in",
"str",
"(",
"annopoint",
".",
"dtype",
")",
":",
"vis",
"=",
"[",
"v",
"[",
"0",
"]",
"if",
"v",
".",
"size",
">",
"0",
"else",
"[",
"0",
"]",
"for",
"v",
"in",
"annopoint",
"[",
"'is_visible'",
"]",
"[",
"0",
"]",
"]",
"vis",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"int",
"(",
"v",
"[",
"0",
"]",
")",
")",
"if",
"len",
"(",
"v",
")",
">",
"0",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"zip",
"(",
"j_id",
",",
"vis",
")",
"]",
")",
"else",
":",
"vis",
"=",
"None",
"# if len(joint_pos) == 16:",
"if",
"(",
"(",
"is_16_pos_only",
"==",
"True",
")",
"and",
"(",
"len",
"(",
"joint_pos",
")",
"==",
"16",
")",
")",
"or",
"(",
"is_16_pos_only",
"==",
"False",
")",
":",
"# only use image with 16 key points / or use all",
"data",
"=",
"{",
"'filename'",
":",
"img_fn",
",",
"'train'",
":",
"train_flag",
",",
"'head_rect'",
":",
"head_rect",
",",
"'is_visible'",
":",
"vis",
",",
"'joint_pos'",
":",
"joint_pos",
"}",
"# print(json.dumps(data), file=fp) # py3",
"if",
"train_flag",
":",
"ann_train_list",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"data",
")",
"else",
":",
"ann_test_list",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"data",
")",
"# def write_line(datum, fp):",
"# joints = sorted([[int(k), v] for k, v in datum['joint_pos'].items()])",
"# joints = np.array([j for i, j in joints]).flatten()",
"#",
"# out = [datum['filename']]",
"# out.extend(joints)",
"# out = [str(o) for o in out]",
"# out = ','.join(out)",
"#",
"# print(out, file=fp)",
"# def split_train_test():",
"# # fp_test = open('data/mpii/test_joints.csv', 'w')",
"# fp_test = open(os.path.join(path, 'test_joints.csv'), 'w')",
"# # fp_train = open('data/mpii/train_joints.csv', 'w')",
"# fp_train = open(os.path.join(path, 'train_joints.csv'), 'w')",
"# # all_data = open('data/mpii/data.json').readlines()",
"# all_data = open(os.path.join(path, 'data.json')).readlines()",
"# N = len(all_data)",
"# N_test = int(N * 0.1)",
"# N_train = N - N_test",
"#",
"# print('N:{}'.format(N))",
"# print('N_train:{}'.format(N_train))",
"# print('N_test:{}'.format(N_test))",
"#",
"# np.random.seed(1701)",
"# perm = np.random.permutation(N)",
"# test_indices = perm[:N_test]",
"# train_indices = perm[N_test:]",
"#",
"# print('train_indices:{}'.format(len(train_indices)))",
"# print('test_indices:{}'.format(len(test_indices)))",
"#",
"# for i in train_indices:",
"# datum = json.loads(all_data[i].strip())",
"# write_line(datum, fp_train)",
"#",
"# for i in test_indices:",
"# datum = json.loads(all_data[i].strip())",
"# write_line(datum, fp_test)",
"save_joints",
"(",
")",
"# split_train_test() #",
"## read images dir",
"logging",
".",
"info",
"(",
"\"reading images list ...\"",
")",
"img_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"extracted_filename2",
")",
"_img_list",
"=",
"load_file_list",
"(",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"extracted_filename2",
")",
",",
"regx",
"=",
"'\\\\.jpg'",
",",
"printable",
"=",
"False",
")",
"# ann_list = json.load(open(os.path.join(path, 'data.json')))",
"for",
"i",
",",
"im",
"in",
"enumerate",
"(",
"img_train_list",
")",
":",
"if",
"im",
"not",
"in",
"_img_list",
":",
"print",
"(",
"'missing training image {} in {} (remove from img(ann)_train_list)'",
".",
"format",
"(",
"im",
",",
"img_dir",
")",
")",
"# img_train_list.remove(im)",
"del",
"img_train_list",
"[",
"i",
"]",
"del",
"ann_train_list",
"[",
"i",
"]",
"for",
"i",
",",
"im",
"in",
"enumerate",
"(",
"img_test_list",
")",
":",
"if",
"im",
"not",
"in",
"_img_list",
":",
"print",
"(",
"'missing testing image {} in {} (remove from img(ann)_test_list)'",
".",
"format",
"(",
"im",
",",
"img_dir",
")",
")",
"# img_test_list.remove(im)",
"del",
"img_train_list",
"[",
"i",
"]",
"del",
"ann_train_list",
"[",
"i",
"]",
"## check annotation and images",
"n_train_images",
"=",
"len",
"(",
"img_train_list",
")",
"n_test_images",
"=",
"len",
"(",
"img_test_list",
")",
"n_images",
"=",
"n_train_images",
"+",
"n_test_images",
"logging",
".",
"info",
"(",
"\"n_images: {} n_train_images: {} n_test_images: {}\"",
".",
"format",
"(",
"n_images",
",",
"n_train_images",
",",
"n_test_images",
")",
")",
"n_train_ann",
"=",
"len",
"(",
"ann_train_list",
")",
"n_test_ann",
"=",
"len",
"(",
"ann_test_list",
")",
"n_ann",
"=",
"n_train_ann",
"+",
"n_test_ann",
"logging",
".",
"info",
"(",
"\"n_ann: {} n_train_ann: {} n_test_ann: {}\"",
".",
"format",
"(",
"n_ann",
",",
"n_train_ann",
",",
"n_test_ann",
")",
")",
"n_train_people",
"=",
"len",
"(",
"sum",
"(",
"ann_train_list",
",",
"[",
"]",
")",
")",
"n_test_people",
"=",
"len",
"(",
"sum",
"(",
"ann_test_list",
",",
"[",
"]",
")",
")",
"n_people",
"=",
"n_train_people",
"+",
"n_test_people",
"logging",
".",
"info",
"(",
"\"n_people: {} n_train_people: {} n_test_people: {}\"",
".",
"format",
"(",
"n_people",
",",
"n_train_people",
",",
"n_test_people",
")",
")",
"# add path to all image file name",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"img_train_list",
")",
":",
"img_train_list",
"[",
"i",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"img_dir",
",",
"value",
")",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"img_test_list",
")",
":",
"img_test_list",
"[",
"i",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"img_dir",
",",
"value",
")",
"return",
"img_train_list",
",",
"ann_train_list",
",",
"img_test_list",
",",
"ann_test_list"
] | Load MPII Human Pose Dataset.
Parameters
-----------
path : str
The path that the data is downloaded to.
is_16_pos_only : boolean
If True, only return the peoples contain 16 pose keypoints. (Usually be used for single person pose estimation)
Returns
----------
img_train_list : list of str
The image directories of training data.
ann_train_list : list of dict
The annotations of training data.
img_test_list : list of str
The image directories of testing data.
ann_test_list : list of dict
The annotations of testing data.
Examples
--------
>>> import pprint
>>> import tensorlayer as tl
>>> img_train_list, ann_train_list, img_test_list, ann_test_list = tl.files.load_mpii_pose_dataset()
>>> image = tl.vis.read_image(img_train_list[0])
>>> tl.vis.draw_mpii_pose_to_image(image, ann_train_list[0], 'image.png')
>>> pprint.pprint(ann_train_list[0])
References
-----------
- `MPII Human Pose Dataset. CVPR 14 <http://human-pose.mpi-inf.mpg.de>`__
- `MPII Human Pose Models. CVPR 16 <http://pose.mpi-inf.mpg.de>`__
- `MPII Human Shape, Poselet Conditioned Pictorial Structures and etc <http://pose.mpi-inf.mpg.de/#related>`__
- `MPII Keyponts and ID <http://human-pose.mpi-inf.mpg.de/#download>`__ | [
"Load",
"MPII",
"Human",
"Pose",
"Dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/dataset_loaders/mpii_dataset.py#L16-L256 | valid |
tensorlayer/tensorlayer | tensorlayer/layers/spatial_transformer.py | transformer | def transformer(U, theta, out_size, name='SpatialTransformer2dAffine'):
"""Spatial Transformer Layer for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__
, see :class:`SpatialTransformer2dAffineLayer` class.
Parameters
----------
U : list of float
The output of a convolutional net should have the
shape [num_batch, height, width, num_channels].
theta: float
The output of the localisation network should be [num_batch, 6], value range should be [0, 1] (via tanh).
out_size: tuple of int
The size of the output of the network (height, width)
name: str
Optional function name
Returns
-------
Tensor
The transformed tensor.
References
----------
- `Spatial Transformer Networks <https://arxiv.org/abs/1506.02025>`__
- `TensorFlow/Models <https://github.com/tensorflow/models/tree/master/transformer>`__
Notes
-----
To initialize the network to the identity transform init.
>>> import tensorflow as tf
>>> # ``theta`` to
>>> identity = np.array([[1., 0., 0.], [0., 1., 0.]])
>>> identity = identity.flatten()
>>> theta = tf.Variable(initial_value=identity)
"""
def _repeat(x, n_repeats):
with tf.variable_scope('_repeat'):
rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([
n_repeats,
])), 1), [1, 0])
rep = tf.cast(rep, 'int32')
x = tf.matmul(tf.reshape(x, (-1, 1)), rep)
return tf.reshape(x, [-1])
def _interpolate(im, x, y, out_size):
with tf.variable_scope('_interpolate'):
# constants
num_batch = tf.shape(im)[0]
height = tf.shape(im)[1]
width = tf.shape(im)[2]
channels = tf.shape(im)[3]
x = tf.cast(x, 'float32')
y = tf.cast(y, 'float32')
height_f = tf.cast(height, 'float32')
width_f = tf.cast(width, 'float32')
out_height = out_size[0]
out_width = out_size[1]
zero = tf.zeros([], dtype='int32')
max_y = tf.cast(tf.shape(im)[1] - 1, 'int32')
max_x = tf.cast(tf.shape(im)[2] - 1, 'int32')
# scale indices from [-1, 1] to [0, width/height]
x = (x + 1.0) * (width_f) / 2.0
y = (y + 1.0) * (height_f) / 2.0
# do sampling
x0 = tf.cast(tf.floor(x), 'int32')
x1 = x0 + 1
y0 = tf.cast(tf.floor(y), 'int32')
y1 = y0 + 1
x0 = tf.clip_by_value(x0, zero, max_x)
x1 = tf.clip_by_value(x1, zero, max_x)
y0 = tf.clip_by_value(y0, zero, max_y)
y1 = tf.clip_by_value(y1, zero, max_y)
dim2 = width
dim1 = width * height
base = _repeat(tf.range(num_batch) * dim1, out_height * out_width)
base_y0 = base + y0 * dim2
base_y1 = base + y1 * dim2
idx_a = base_y0 + x0
idx_b = base_y1 + x0
idx_c = base_y0 + x1
idx_d = base_y1 + x1
# use indices to lookup pixels in the flat image and restore
# channels dim
im_flat = tf.reshape(im, tf.stack([-1, channels]))
im_flat = tf.cast(im_flat, 'float32')
Ia = tf.gather(im_flat, idx_a)
Ib = tf.gather(im_flat, idx_b)
Ic = tf.gather(im_flat, idx_c)
Id = tf.gather(im_flat, idx_d)
# and finally calculate interpolated values
x0_f = tf.cast(x0, 'float32')
x1_f = tf.cast(x1, 'float32')
y0_f = tf.cast(y0, 'float32')
y1_f = tf.cast(y1, 'float32')
wa = tf.expand_dims(((x1_f - x) * (y1_f - y)), 1)
wb = tf.expand_dims(((x1_f - x) * (y - y0_f)), 1)
wc = tf.expand_dims(((x - x0_f) * (y1_f - y)), 1)
wd = tf.expand_dims(((x - x0_f) * (y - y0_f)), 1)
output = tf.add_n([wa * Ia, wb * Ib, wc * Ic, wd * Id])
return output
def _meshgrid(height, width):
with tf.variable_scope('_meshgrid'):
# This should be equivalent to:
# x_t, y_t = np.meshgrid(np.linspace(-1, 1, width),
# np.linspace(-1, 1, height))
# ones = np.ones(np.prod(x_t.shape))
# grid = np.vstack([x_t.flatten(), y_t.flatten(), ones])
x_t = tf.matmul(
tf.ones(shape=tf.stack([height, 1])),
tf.transpose(tf.expand_dims(tf.linspace(-1.0, 1.0, width), 1), [1, 0])
)
y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1), tf.ones(shape=tf.stack([1, width])))
x_t_flat = tf.reshape(x_t, (1, -1))
y_t_flat = tf.reshape(y_t, (1, -1))
ones = tf.ones_like(x_t_flat)
grid = tf.concat(axis=0, values=[x_t_flat, y_t_flat, ones])
return grid
def _transform(theta, input_dim, out_size):
with tf.variable_scope('_transform'):
num_batch = tf.shape(input_dim)[0]
num_channels = tf.shape(input_dim)[3]
theta = tf.reshape(theta, (-1, 2, 3))
theta = tf.cast(theta, 'float32')
# grid of (x_t, y_t, 1), eq (1) in ref [1]
out_height = out_size[0]
out_width = out_size[1]
grid = _meshgrid(out_height, out_width)
grid = tf.expand_dims(grid, 0)
grid = tf.reshape(grid, [-1])
grid = tf.tile(grid, tf.stack([num_batch]))
grid = tf.reshape(grid, tf.stack([num_batch, 3, -1]))
# Transform A x (x_t, y_t, 1)^T -> (x_s, y_s)
T_g = tf.matmul(theta, grid)
x_s = tf.slice(T_g, [0, 0, 0], [-1, 1, -1])
y_s = tf.slice(T_g, [0, 1, 0], [-1, 1, -1])
x_s_flat = tf.reshape(x_s, [-1])
y_s_flat = tf.reshape(y_s, [-1])
input_transformed = _interpolate(input_dim, x_s_flat, y_s_flat, out_size)
output = tf.reshape(input_transformed, tf.stack([num_batch, out_height, out_width, num_channels]))
return output
with tf.variable_scope(name):
output = _transform(theta, U, out_size)
return output | python | def transformer(U, theta, out_size, name='SpatialTransformer2dAffine'):
"""Spatial Transformer Layer for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__
, see :class:`SpatialTransformer2dAffineLayer` class.
Parameters
----------
U : list of float
The output of a convolutional net should have the
shape [num_batch, height, width, num_channels].
theta: float
The output of the localisation network should be [num_batch, 6], value range should be [0, 1] (via tanh).
out_size: tuple of int
The size of the output of the network (height, width)
name: str
Optional function name
Returns
-------
Tensor
The transformed tensor.
References
----------
- `Spatial Transformer Networks <https://arxiv.org/abs/1506.02025>`__
- `TensorFlow/Models <https://github.com/tensorflow/models/tree/master/transformer>`__
Notes
-----
To initialize the network to the identity transform init.
>>> import tensorflow as tf
>>> # ``theta`` to
>>> identity = np.array([[1., 0., 0.], [0., 1., 0.]])
>>> identity = identity.flatten()
>>> theta = tf.Variable(initial_value=identity)
"""
def _repeat(x, n_repeats):
with tf.variable_scope('_repeat'):
rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([
n_repeats,
])), 1), [1, 0])
rep = tf.cast(rep, 'int32')
x = tf.matmul(tf.reshape(x, (-1, 1)), rep)
return tf.reshape(x, [-1])
def _interpolate(im, x, y, out_size):
with tf.variable_scope('_interpolate'):
# constants
num_batch = tf.shape(im)[0]
height = tf.shape(im)[1]
width = tf.shape(im)[2]
channels = tf.shape(im)[3]
x = tf.cast(x, 'float32')
y = tf.cast(y, 'float32')
height_f = tf.cast(height, 'float32')
width_f = tf.cast(width, 'float32')
out_height = out_size[0]
out_width = out_size[1]
zero = tf.zeros([], dtype='int32')
max_y = tf.cast(tf.shape(im)[1] - 1, 'int32')
max_x = tf.cast(tf.shape(im)[2] - 1, 'int32')
# scale indices from [-1, 1] to [0, width/height]
x = (x + 1.0) * (width_f) / 2.0
y = (y + 1.0) * (height_f) / 2.0
# do sampling
x0 = tf.cast(tf.floor(x), 'int32')
x1 = x0 + 1
y0 = tf.cast(tf.floor(y), 'int32')
y1 = y0 + 1
x0 = tf.clip_by_value(x0, zero, max_x)
x1 = tf.clip_by_value(x1, zero, max_x)
y0 = tf.clip_by_value(y0, zero, max_y)
y1 = tf.clip_by_value(y1, zero, max_y)
dim2 = width
dim1 = width * height
base = _repeat(tf.range(num_batch) * dim1, out_height * out_width)
base_y0 = base + y0 * dim2
base_y1 = base + y1 * dim2
idx_a = base_y0 + x0
idx_b = base_y1 + x0
idx_c = base_y0 + x1
idx_d = base_y1 + x1
# use indices to lookup pixels in the flat image and restore
# channels dim
im_flat = tf.reshape(im, tf.stack([-1, channels]))
im_flat = tf.cast(im_flat, 'float32')
Ia = tf.gather(im_flat, idx_a)
Ib = tf.gather(im_flat, idx_b)
Ic = tf.gather(im_flat, idx_c)
Id = tf.gather(im_flat, idx_d)
# and finally calculate interpolated values
x0_f = tf.cast(x0, 'float32')
x1_f = tf.cast(x1, 'float32')
y0_f = tf.cast(y0, 'float32')
y1_f = tf.cast(y1, 'float32')
wa = tf.expand_dims(((x1_f - x) * (y1_f - y)), 1)
wb = tf.expand_dims(((x1_f - x) * (y - y0_f)), 1)
wc = tf.expand_dims(((x - x0_f) * (y1_f - y)), 1)
wd = tf.expand_dims(((x - x0_f) * (y - y0_f)), 1)
output = tf.add_n([wa * Ia, wb * Ib, wc * Ic, wd * Id])
return output
def _meshgrid(height, width):
with tf.variable_scope('_meshgrid'):
# This should be equivalent to:
# x_t, y_t = np.meshgrid(np.linspace(-1, 1, width),
# np.linspace(-1, 1, height))
# ones = np.ones(np.prod(x_t.shape))
# grid = np.vstack([x_t.flatten(), y_t.flatten(), ones])
x_t = tf.matmul(
tf.ones(shape=tf.stack([height, 1])),
tf.transpose(tf.expand_dims(tf.linspace(-1.0, 1.0, width), 1), [1, 0])
)
y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1), tf.ones(shape=tf.stack([1, width])))
x_t_flat = tf.reshape(x_t, (1, -1))
y_t_flat = tf.reshape(y_t, (1, -1))
ones = tf.ones_like(x_t_flat)
grid = tf.concat(axis=0, values=[x_t_flat, y_t_flat, ones])
return grid
def _transform(theta, input_dim, out_size):
with tf.variable_scope('_transform'):
num_batch = tf.shape(input_dim)[0]
num_channels = tf.shape(input_dim)[3]
theta = tf.reshape(theta, (-1, 2, 3))
theta = tf.cast(theta, 'float32')
# grid of (x_t, y_t, 1), eq (1) in ref [1]
out_height = out_size[0]
out_width = out_size[1]
grid = _meshgrid(out_height, out_width)
grid = tf.expand_dims(grid, 0)
grid = tf.reshape(grid, [-1])
grid = tf.tile(grid, tf.stack([num_batch]))
grid = tf.reshape(grid, tf.stack([num_batch, 3, -1]))
# Transform A x (x_t, y_t, 1)^T -> (x_s, y_s)
T_g = tf.matmul(theta, grid)
x_s = tf.slice(T_g, [0, 0, 0], [-1, 1, -1])
y_s = tf.slice(T_g, [0, 1, 0], [-1, 1, -1])
x_s_flat = tf.reshape(x_s, [-1])
y_s_flat = tf.reshape(y_s, [-1])
input_transformed = _interpolate(input_dim, x_s_flat, y_s_flat, out_size)
output = tf.reshape(input_transformed, tf.stack([num_batch, out_height, out_width, num_channels]))
return output
with tf.variable_scope(name):
output = _transform(theta, U, out_size)
return output | [
"def",
"transformer",
"(",
"U",
",",
"theta",
",",
"out_size",
",",
"name",
"=",
"'SpatialTransformer2dAffine'",
")",
":",
"def",
"_repeat",
"(",
"x",
",",
"n_repeats",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'_repeat'",
")",
":",
"rep",
"=",
"tf",
".",
"transpose",
"(",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"ones",
"(",
"shape",
"=",
"tf",
".",
"stack",
"(",
"[",
"n_repeats",
",",
"]",
")",
")",
",",
"1",
")",
",",
"[",
"1",
",",
"0",
"]",
")",
"rep",
"=",
"tf",
".",
"cast",
"(",
"rep",
",",
"'int32'",
")",
"x",
"=",
"tf",
".",
"matmul",
"(",
"tf",
".",
"reshape",
"(",
"x",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
",",
"rep",
")",
"return",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
"]",
")",
"def",
"_interpolate",
"(",
"im",
",",
"x",
",",
"y",
",",
"out_size",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'_interpolate'",
")",
":",
"# constants",
"num_batch",
"=",
"tf",
".",
"shape",
"(",
"im",
")",
"[",
"0",
"]",
"height",
"=",
"tf",
".",
"shape",
"(",
"im",
")",
"[",
"1",
"]",
"width",
"=",
"tf",
".",
"shape",
"(",
"im",
")",
"[",
"2",
"]",
"channels",
"=",
"tf",
".",
"shape",
"(",
"im",
")",
"[",
"3",
"]",
"x",
"=",
"tf",
".",
"cast",
"(",
"x",
",",
"'float32'",
")",
"y",
"=",
"tf",
".",
"cast",
"(",
"y",
",",
"'float32'",
")",
"height_f",
"=",
"tf",
".",
"cast",
"(",
"height",
",",
"'float32'",
")",
"width_f",
"=",
"tf",
".",
"cast",
"(",
"width",
",",
"'float32'",
")",
"out_height",
"=",
"out_size",
"[",
"0",
"]",
"out_width",
"=",
"out_size",
"[",
"1",
"]",
"zero",
"=",
"tf",
".",
"zeros",
"(",
"[",
"]",
",",
"dtype",
"=",
"'int32'",
")",
"max_y",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"shape",
"(",
"im",
")",
"[",
"1",
"]",
"-",
"1",
",",
"'int32'",
")",
"max_x",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"shape",
"(",
"im",
")",
"[",
"2",
"]",
"-",
"1",
",",
"'int32'",
")",
"# scale indices from [-1, 1] to [0, width/height]",
"x",
"=",
"(",
"x",
"+",
"1.0",
")",
"*",
"(",
"width_f",
")",
"/",
"2.0",
"y",
"=",
"(",
"y",
"+",
"1.0",
")",
"*",
"(",
"height_f",
")",
"/",
"2.0",
"# do sampling",
"x0",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"floor",
"(",
"x",
")",
",",
"'int32'",
")",
"x1",
"=",
"x0",
"+",
"1",
"y0",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"floor",
"(",
"y",
")",
",",
"'int32'",
")",
"y1",
"=",
"y0",
"+",
"1",
"x0",
"=",
"tf",
".",
"clip_by_value",
"(",
"x0",
",",
"zero",
",",
"max_x",
")",
"x1",
"=",
"tf",
".",
"clip_by_value",
"(",
"x1",
",",
"zero",
",",
"max_x",
")",
"y0",
"=",
"tf",
".",
"clip_by_value",
"(",
"y0",
",",
"zero",
",",
"max_y",
")",
"y1",
"=",
"tf",
".",
"clip_by_value",
"(",
"y1",
",",
"zero",
",",
"max_y",
")",
"dim2",
"=",
"width",
"dim1",
"=",
"width",
"*",
"height",
"base",
"=",
"_repeat",
"(",
"tf",
".",
"range",
"(",
"num_batch",
")",
"*",
"dim1",
",",
"out_height",
"*",
"out_width",
")",
"base_y0",
"=",
"base",
"+",
"y0",
"*",
"dim2",
"base_y1",
"=",
"base",
"+",
"y1",
"*",
"dim2",
"idx_a",
"=",
"base_y0",
"+",
"x0",
"idx_b",
"=",
"base_y1",
"+",
"x0",
"idx_c",
"=",
"base_y0",
"+",
"x1",
"idx_d",
"=",
"base_y1",
"+",
"x1",
"# use indices to lookup pixels in the flat image and restore",
"# channels dim",
"im_flat",
"=",
"tf",
".",
"reshape",
"(",
"im",
",",
"tf",
".",
"stack",
"(",
"[",
"-",
"1",
",",
"channels",
"]",
")",
")",
"im_flat",
"=",
"tf",
".",
"cast",
"(",
"im_flat",
",",
"'float32'",
")",
"Ia",
"=",
"tf",
".",
"gather",
"(",
"im_flat",
",",
"idx_a",
")",
"Ib",
"=",
"tf",
".",
"gather",
"(",
"im_flat",
",",
"idx_b",
")",
"Ic",
"=",
"tf",
".",
"gather",
"(",
"im_flat",
",",
"idx_c",
")",
"Id",
"=",
"tf",
".",
"gather",
"(",
"im_flat",
",",
"idx_d",
")",
"# and finally calculate interpolated values",
"x0_f",
"=",
"tf",
".",
"cast",
"(",
"x0",
",",
"'float32'",
")",
"x1_f",
"=",
"tf",
".",
"cast",
"(",
"x1",
",",
"'float32'",
")",
"y0_f",
"=",
"tf",
".",
"cast",
"(",
"y0",
",",
"'float32'",
")",
"y1_f",
"=",
"tf",
".",
"cast",
"(",
"y1",
",",
"'float32'",
")",
"wa",
"=",
"tf",
".",
"expand_dims",
"(",
"(",
"(",
"x1_f",
"-",
"x",
")",
"*",
"(",
"y1_f",
"-",
"y",
")",
")",
",",
"1",
")",
"wb",
"=",
"tf",
".",
"expand_dims",
"(",
"(",
"(",
"x1_f",
"-",
"x",
")",
"*",
"(",
"y",
"-",
"y0_f",
")",
")",
",",
"1",
")",
"wc",
"=",
"tf",
".",
"expand_dims",
"(",
"(",
"(",
"x",
"-",
"x0_f",
")",
"*",
"(",
"y1_f",
"-",
"y",
")",
")",
",",
"1",
")",
"wd",
"=",
"tf",
".",
"expand_dims",
"(",
"(",
"(",
"x",
"-",
"x0_f",
")",
"*",
"(",
"y",
"-",
"y0_f",
")",
")",
",",
"1",
")",
"output",
"=",
"tf",
".",
"add_n",
"(",
"[",
"wa",
"*",
"Ia",
",",
"wb",
"*",
"Ib",
",",
"wc",
"*",
"Ic",
",",
"wd",
"*",
"Id",
"]",
")",
"return",
"output",
"def",
"_meshgrid",
"(",
"height",
",",
"width",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'_meshgrid'",
")",
":",
"# This should be equivalent to:",
"# x_t, y_t = np.meshgrid(np.linspace(-1, 1, width),",
"# np.linspace(-1, 1, height))",
"# ones = np.ones(np.prod(x_t.shape))",
"# grid = np.vstack([x_t.flatten(), y_t.flatten(), ones])",
"x_t",
"=",
"tf",
".",
"matmul",
"(",
"tf",
".",
"ones",
"(",
"shape",
"=",
"tf",
".",
"stack",
"(",
"[",
"height",
",",
"1",
"]",
")",
")",
",",
"tf",
".",
"transpose",
"(",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"linspace",
"(",
"-",
"1.0",
",",
"1.0",
",",
"width",
")",
",",
"1",
")",
",",
"[",
"1",
",",
"0",
"]",
")",
")",
"y_t",
"=",
"tf",
".",
"matmul",
"(",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"linspace",
"(",
"-",
"1.0",
",",
"1.0",
",",
"height",
")",
",",
"1",
")",
",",
"tf",
".",
"ones",
"(",
"shape",
"=",
"tf",
".",
"stack",
"(",
"[",
"1",
",",
"width",
"]",
")",
")",
")",
"x_t_flat",
"=",
"tf",
".",
"reshape",
"(",
"x_t",
",",
"(",
"1",
",",
"-",
"1",
")",
")",
"y_t_flat",
"=",
"tf",
".",
"reshape",
"(",
"y_t",
",",
"(",
"1",
",",
"-",
"1",
")",
")",
"ones",
"=",
"tf",
".",
"ones_like",
"(",
"x_t_flat",
")",
"grid",
"=",
"tf",
".",
"concat",
"(",
"axis",
"=",
"0",
",",
"values",
"=",
"[",
"x_t_flat",
",",
"y_t_flat",
",",
"ones",
"]",
")",
"return",
"grid",
"def",
"_transform",
"(",
"theta",
",",
"input_dim",
",",
"out_size",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'_transform'",
")",
":",
"num_batch",
"=",
"tf",
".",
"shape",
"(",
"input_dim",
")",
"[",
"0",
"]",
"num_channels",
"=",
"tf",
".",
"shape",
"(",
"input_dim",
")",
"[",
"3",
"]",
"theta",
"=",
"tf",
".",
"reshape",
"(",
"theta",
",",
"(",
"-",
"1",
",",
"2",
",",
"3",
")",
")",
"theta",
"=",
"tf",
".",
"cast",
"(",
"theta",
",",
"'float32'",
")",
"# grid of (x_t, y_t, 1), eq (1) in ref [1]",
"out_height",
"=",
"out_size",
"[",
"0",
"]",
"out_width",
"=",
"out_size",
"[",
"1",
"]",
"grid",
"=",
"_meshgrid",
"(",
"out_height",
",",
"out_width",
")",
"grid",
"=",
"tf",
".",
"expand_dims",
"(",
"grid",
",",
"0",
")",
"grid",
"=",
"tf",
".",
"reshape",
"(",
"grid",
",",
"[",
"-",
"1",
"]",
")",
"grid",
"=",
"tf",
".",
"tile",
"(",
"grid",
",",
"tf",
".",
"stack",
"(",
"[",
"num_batch",
"]",
")",
")",
"grid",
"=",
"tf",
".",
"reshape",
"(",
"grid",
",",
"tf",
".",
"stack",
"(",
"[",
"num_batch",
",",
"3",
",",
"-",
"1",
"]",
")",
")",
"# Transform A x (x_t, y_t, 1)^T -> (x_s, y_s)",
"T_g",
"=",
"tf",
".",
"matmul",
"(",
"theta",
",",
"grid",
")",
"x_s",
"=",
"tf",
".",
"slice",
"(",
"T_g",
",",
"[",
"0",
",",
"0",
",",
"0",
"]",
",",
"[",
"-",
"1",
",",
"1",
",",
"-",
"1",
"]",
")",
"y_s",
"=",
"tf",
".",
"slice",
"(",
"T_g",
",",
"[",
"0",
",",
"1",
",",
"0",
"]",
",",
"[",
"-",
"1",
",",
"1",
",",
"-",
"1",
"]",
")",
"x_s_flat",
"=",
"tf",
".",
"reshape",
"(",
"x_s",
",",
"[",
"-",
"1",
"]",
")",
"y_s_flat",
"=",
"tf",
".",
"reshape",
"(",
"y_s",
",",
"[",
"-",
"1",
"]",
")",
"input_transformed",
"=",
"_interpolate",
"(",
"input_dim",
",",
"x_s_flat",
",",
"y_s_flat",
",",
"out_size",
")",
"output",
"=",
"tf",
".",
"reshape",
"(",
"input_transformed",
",",
"tf",
".",
"stack",
"(",
"[",
"num_batch",
",",
"out_height",
",",
"out_width",
",",
"num_channels",
"]",
")",
")",
"return",
"output",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"output",
"=",
"_transform",
"(",
"theta",
",",
"U",
",",
"out_size",
")",
"return",
"output"
] | Spatial Transformer Layer for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__
, see :class:`SpatialTransformer2dAffineLayer` class.
Parameters
----------
U : list of float
The output of a convolutional net should have the
shape [num_batch, height, width, num_channels].
theta: float
The output of the localisation network should be [num_batch, 6], value range should be [0, 1] (via tanh).
out_size: tuple of int
The size of the output of the network (height, width)
name: str
Optional function name
Returns
-------
Tensor
The transformed tensor.
References
----------
- `Spatial Transformer Networks <https://arxiv.org/abs/1506.02025>`__
- `TensorFlow/Models <https://github.com/tensorflow/models/tree/master/transformer>`__
Notes
-----
To initialize the network to the identity transform init.
>>> import tensorflow as tf
>>> # ``theta`` to
>>> identity = np.array([[1., 0., 0.], [0., 1., 0.]])
>>> identity = identity.flatten()
>>> theta = tf.Variable(initial_value=identity) | [
"Spatial",
"Transformer",
"Layer",
"for",
"2D",
"Affine",
"Transformation",
"<https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Affine_transformation",
">",
"__",
"see",
":",
"class",
":",
"SpatialTransformer2dAffineLayer",
"class",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/spatial_transformer.py#L28-L188 | valid |
tensorlayer/tensorlayer | tensorlayer/layers/spatial_transformer.py | batch_transformer | def batch_transformer(U, thetas, out_size, name='BatchSpatialTransformer2dAffine'):
"""Batch Spatial Transformer function for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__.
Parameters
----------
U : list of float
tensor of inputs [batch, height, width, num_channels]
thetas : list of float
a set of transformations for each input [batch, num_transforms, 6]
out_size : list of int
the size of the output [out_height, out_width]
name : str
optional function name
Returns
------
float
Tensor of size [batch * num_transforms, out_height, out_width, num_channels]
"""
with tf.variable_scope(name):
num_batch, num_transforms = map(int, thetas.get_shape().as_list()[:2])
indices = [[i] * num_transforms for i in xrange(num_batch)]
input_repeated = tf.gather(U, tf.reshape(indices, [-1]))
return transformer(input_repeated, thetas, out_size) | python | def batch_transformer(U, thetas, out_size, name='BatchSpatialTransformer2dAffine'):
"""Batch Spatial Transformer function for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__.
Parameters
----------
U : list of float
tensor of inputs [batch, height, width, num_channels]
thetas : list of float
a set of transformations for each input [batch, num_transforms, 6]
out_size : list of int
the size of the output [out_height, out_width]
name : str
optional function name
Returns
------
float
Tensor of size [batch * num_transforms, out_height, out_width, num_channels]
"""
with tf.variable_scope(name):
num_batch, num_transforms = map(int, thetas.get_shape().as_list()[:2])
indices = [[i] * num_transforms for i in xrange(num_batch)]
input_repeated = tf.gather(U, tf.reshape(indices, [-1]))
return transformer(input_repeated, thetas, out_size) | [
"def",
"batch_transformer",
"(",
"U",
",",
"thetas",
",",
"out_size",
",",
"name",
"=",
"'BatchSpatialTransformer2dAffine'",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
")",
":",
"num_batch",
",",
"num_transforms",
"=",
"map",
"(",
"int",
",",
"thetas",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
":",
"2",
"]",
")",
"indices",
"=",
"[",
"[",
"i",
"]",
"*",
"num_transforms",
"for",
"i",
"in",
"xrange",
"(",
"num_batch",
")",
"]",
"input_repeated",
"=",
"tf",
".",
"gather",
"(",
"U",
",",
"tf",
".",
"reshape",
"(",
"indices",
",",
"[",
"-",
"1",
"]",
")",
")",
"return",
"transformer",
"(",
"input_repeated",
",",
"thetas",
",",
"out_size",
")"
] | Batch Spatial Transformer function for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__.
Parameters
----------
U : list of float
tensor of inputs [batch, height, width, num_channels]
thetas : list of float
a set of transformations for each input [batch, num_transforms, 6]
out_size : list of int
the size of the output [out_height, out_width]
name : str
optional function name
Returns
------
float
Tensor of size [batch * num_transforms, out_height, out_width, num_channels] | [
"Batch",
"Spatial",
"Transformer",
"function",
"for",
"2D",
"Affine",
"Transformation",
"<https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Affine_transformation",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/spatial_transformer.py#L191-L215 | valid |
tensorlayer/tensorlayer | tensorlayer/distributed.py | create_task_spec_def | def create_task_spec_def():
"""Returns the a :class:`TaskSpecDef` based on the environment variables for distributed training.
References
----------
- `ML-engine trainer considerations <https://cloud.google.com/ml-engine/docs/trainer-considerations#use_tf_config>`__
- `TensorPort Distributed Computing <https://www.tensorport.com/documentation/code-details/>`__
"""
if 'TF_CONFIG' in os.environ:
# TF_CONFIG is used in ML-engine
env = json.loads(os.environ.get('TF_CONFIG', '{}'))
task_data = env.get('task', None) or {'type': 'master', 'index': 0}
cluster_data = env.get('cluster', None) or {'ps': None, 'worker': None, 'master': None}
return TaskSpecDef(
task_type=task_data['type'], index=task_data['index'],
trial=task_data['trial'] if 'trial' in task_data else None, ps_hosts=cluster_data['ps'],
worker_hosts=cluster_data['worker'], master=cluster_data['master'] if 'master' in cluster_data else None
)
elif 'JOB_NAME' in os.environ:
# JOB_NAME, TASK_INDEX, PS_HOSTS, WORKER_HOSTS and MASTER_HOST are used in TensorPort
return TaskSpecDef(
task_type=os.environ['JOB_NAME'], index=os.environ['TASK_INDEX'], ps_hosts=os.environ.get('PS_HOSTS', None),
worker_hosts=os.environ.get('WORKER_HOSTS', None), master=os.environ.get('MASTER_HOST', None)
)
else:
raise Exception('You need to setup TF_CONFIG or JOB_NAME to define the task.') | python | def create_task_spec_def():
"""Returns the a :class:`TaskSpecDef` based on the environment variables for distributed training.
References
----------
- `ML-engine trainer considerations <https://cloud.google.com/ml-engine/docs/trainer-considerations#use_tf_config>`__
- `TensorPort Distributed Computing <https://www.tensorport.com/documentation/code-details/>`__
"""
if 'TF_CONFIG' in os.environ:
# TF_CONFIG is used in ML-engine
env = json.loads(os.environ.get('TF_CONFIG', '{}'))
task_data = env.get('task', None) or {'type': 'master', 'index': 0}
cluster_data = env.get('cluster', None) or {'ps': None, 'worker': None, 'master': None}
return TaskSpecDef(
task_type=task_data['type'], index=task_data['index'],
trial=task_data['trial'] if 'trial' in task_data else None, ps_hosts=cluster_data['ps'],
worker_hosts=cluster_data['worker'], master=cluster_data['master'] if 'master' in cluster_data else None
)
elif 'JOB_NAME' in os.environ:
# JOB_NAME, TASK_INDEX, PS_HOSTS, WORKER_HOSTS and MASTER_HOST are used in TensorPort
return TaskSpecDef(
task_type=os.environ['JOB_NAME'], index=os.environ['TASK_INDEX'], ps_hosts=os.environ.get('PS_HOSTS', None),
worker_hosts=os.environ.get('WORKER_HOSTS', None), master=os.environ.get('MASTER_HOST', None)
)
else:
raise Exception('You need to setup TF_CONFIG or JOB_NAME to define the task.') | [
"def",
"create_task_spec_def",
"(",
")",
":",
"if",
"'TF_CONFIG'",
"in",
"os",
".",
"environ",
":",
"# TF_CONFIG is used in ML-engine",
"env",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'TF_CONFIG'",
",",
"'{}'",
")",
")",
"task_data",
"=",
"env",
".",
"get",
"(",
"'task'",
",",
"None",
")",
"or",
"{",
"'type'",
":",
"'master'",
",",
"'index'",
":",
"0",
"}",
"cluster_data",
"=",
"env",
".",
"get",
"(",
"'cluster'",
",",
"None",
")",
"or",
"{",
"'ps'",
":",
"None",
",",
"'worker'",
":",
"None",
",",
"'master'",
":",
"None",
"}",
"return",
"TaskSpecDef",
"(",
"task_type",
"=",
"task_data",
"[",
"'type'",
"]",
",",
"index",
"=",
"task_data",
"[",
"'index'",
"]",
",",
"trial",
"=",
"task_data",
"[",
"'trial'",
"]",
"if",
"'trial'",
"in",
"task_data",
"else",
"None",
",",
"ps_hosts",
"=",
"cluster_data",
"[",
"'ps'",
"]",
",",
"worker_hosts",
"=",
"cluster_data",
"[",
"'worker'",
"]",
",",
"master",
"=",
"cluster_data",
"[",
"'master'",
"]",
"if",
"'master'",
"in",
"cluster_data",
"else",
"None",
")",
"elif",
"'JOB_NAME'",
"in",
"os",
".",
"environ",
":",
"# JOB_NAME, TASK_INDEX, PS_HOSTS, WORKER_HOSTS and MASTER_HOST are used in TensorPort",
"return",
"TaskSpecDef",
"(",
"task_type",
"=",
"os",
".",
"environ",
"[",
"'JOB_NAME'",
"]",
",",
"index",
"=",
"os",
".",
"environ",
"[",
"'TASK_INDEX'",
"]",
",",
"ps_hosts",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PS_HOSTS'",
",",
"None",
")",
",",
"worker_hosts",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'WORKER_HOSTS'",
",",
"None",
")",
",",
"master",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'MASTER_HOST'",
",",
"None",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"'You need to setup TF_CONFIG or JOB_NAME to define the task.'",
")"
] | Returns the a :class:`TaskSpecDef` based on the environment variables for distributed training.
References
----------
- `ML-engine trainer considerations <https://cloud.google.com/ml-engine/docs/trainer-considerations#use_tf_config>`__
- `TensorPort Distributed Computing <https://www.tensorport.com/documentation/code-details/>`__ | [
"Returns",
"the",
"a",
":",
"class",
":",
"TaskSpecDef",
"based",
"on",
"the",
"environment",
"variables",
"for",
"distributed",
"training",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/distributed.py#L368-L394 | valid |
tensorlayer/tensorlayer | tensorlayer/distributed.py | create_distributed_session | def create_distributed_session(
task_spec=None, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=600,
save_summaries_steps=object(), save_summaries_secs=object(), config=None, stop_grace_period_secs=120,
log_step_count_steps=100
):
"""Creates a distributed session.
It calls `MonitoredTrainingSession` to create a :class:`MonitoredSession` for distributed training.
Parameters
----------
task_spec : :class:`TaskSpecDef`.
The task spec definition from create_task_spec_def()
checkpoint_dir : str.
Optional path to a directory where to restore variables.
scaffold : ``Scaffold``
A `Scaffold` used for gathering or building supportive ops.
If not specified, a default one is created. It's used to finalize the graph.
hooks : list of ``SessionRunHook`` objects.
Optional
chief_only_hooks : list of ``SessionRunHook`` objects.
Activate these hooks if `is_chief==True`, ignore otherwise.
save_checkpoint_secs : int
The frequency, in seconds, that a checkpoint is saved
using a default checkpoint saver. If `save_checkpoint_secs` is set to
`None`, then the default checkpoint saver isn't used.
save_summaries_steps : int
The frequency, in number of global steps, that the
summaries are written to disk using a default summary saver. If both
`save_summaries_steps` and `save_summaries_secs` are set to `None`, then
the default summary saver isn't used. Default 100.
save_summaries_secs : int
The frequency, in secs, that the summaries are written
to disk using a default summary saver. If both `save_summaries_steps` and
`save_summaries_secs` are set to `None`, then the default summary saver
isn't used. Default not enabled.
config : ``tf.ConfigProto``
an instance of `tf.ConfigProto` proto used to configure the session.
It's the `config` argument of constructor of `tf.Session`.
stop_grace_period_secs : int
Number of seconds given to threads to stop after
`close()` has been called.
log_step_count_steps : int
The frequency, in number of global steps, that the
global step/sec is logged.
Examples
--------
A simple example for distributed training where all the workers use the same dataset:
>>> task_spec = TaskSpec()
>>> with tf.device(task_spec.device_fn()):
>>> tensors = create_graph()
>>> with tl.DistributedSession(task_spec=task_spec,
... checkpoint_dir='/tmp/ckpt') as session:
>>> while not session.should_stop():
>>> session.run(tensors)
An example where the dataset is shared among the workers
(see https://www.tensorflow.org/programmers_guide/datasets):
>>> task_spec = TaskSpec()
>>> # dataset is a :class:`tf.data.Dataset` with the raw data
>>> dataset = create_dataset()
>>> if task_spec is not None:
>>> dataset = dataset.shard(task_spec.num_workers, task_spec.shard_index)
>>> # shuffle or apply a map function to the new sharded dataset, for example:
>>> dataset = dataset.shuffle(buffer_size=10000)
>>> dataset = dataset.batch(batch_size)
>>> dataset = dataset.repeat(num_epochs)
>>> # create the iterator for the dataset and the input tensor
>>> iterator = dataset.make_one_shot_iterator()
>>> next_element = iterator.get_next()
>>> with tf.device(task_spec.device_fn()):
>>> # next_element is the input for the graph
>>> tensors = create_graph(next_element)
>>> with tl.DistributedSession(task_spec=task_spec,
... checkpoint_dir='/tmp/ckpt') as session:
>>> while not session.should_stop():
>>> session.run(tensors)
References
----------
- `MonitoredTrainingSession <https://www.tensorflow.org/api_docs/python/tf/train/MonitoredTrainingSession>`__
"""
target = task_spec.target() if task_spec is not None else None
is_chief = task_spec.is_master() if task_spec is not None else True
return tf.train.MonitoredTrainingSession(
master=target, is_chief=is_chief, checkpoint_dir=checkpoint_dir, scaffold=scaffold,
save_checkpoint_secs=save_checkpoint_secs, save_summaries_steps=save_summaries_steps,
save_summaries_secs=save_summaries_secs, log_step_count_steps=log_step_count_steps,
stop_grace_period_secs=stop_grace_period_secs, config=config, hooks=hooks, chief_only_hooks=chief_only_hooks
) | python | def create_distributed_session(
task_spec=None, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=600,
save_summaries_steps=object(), save_summaries_secs=object(), config=None, stop_grace_period_secs=120,
log_step_count_steps=100
):
"""Creates a distributed session.
It calls `MonitoredTrainingSession` to create a :class:`MonitoredSession` for distributed training.
Parameters
----------
task_spec : :class:`TaskSpecDef`.
The task spec definition from create_task_spec_def()
checkpoint_dir : str.
Optional path to a directory where to restore variables.
scaffold : ``Scaffold``
A `Scaffold` used for gathering or building supportive ops.
If not specified, a default one is created. It's used to finalize the graph.
hooks : list of ``SessionRunHook`` objects.
Optional
chief_only_hooks : list of ``SessionRunHook`` objects.
Activate these hooks if `is_chief==True`, ignore otherwise.
save_checkpoint_secs : int
The frequency, in seconds, that a checkpoint is saved
using a default checkpoint saver. If `save_checkpoint_secs` is set to
`None`, then the default checkpoint saver isn't used.
save_summaries_steps : int
The frequency, in number of global steps, that the
summaries are written to disk using a default summary saver. If both
`save_summaries_steps` and `save_summaries_secs` are set to `None`, then
the default summary saver isn't used. Default 100.
save_summaries_secs : int
The frequency, in secs, that the summaries are written
to disk using a default summary saver. If both `save_summaries_steps` and
`save_summaries_secs` are set to `None`, then the default summary saver
isn't used. Default not enabled.
config : ``tf.ConfigProto``
an instance of `tf.ConfigProto` proto used to configure the session.
It's the `config` argument of constructor of `tf.Session`.
stop_grace_period_secs : int
Number of seconds given to threads to stop after
`close()` has been called.
log_step_count_steps : int
The frequency, in number of global steps, that the
global step/sec is logged.
Examples
--------
A simple example for distributed training where all the workers use the same dataset:
>>> task_spec = TaskSpec()
>>> with tf.device(task_spec.device_fn()):
>>> tensors = create_graph()
>>> with tl.DistributedSession(task_spec=task_spec,
... checkpoint_dir='/tmp/ckpt') as session:
>>> while not session.should_stop():
>>> session.run(tensors)
An example where the dataset is shared among the workers
(see https://www.tensorflow.org/programmers_guide/datasets):
>>> task_spec = TaskSpec()
>>> # dataset is a :class:`tf.data.Dataset` with the raw data
>>> dataset = create_dataset()
>>> if task_spec is not None:
>>> dataset = dataset.shard(task_spec.num_workers, task_spec.shard_index)
>>> # shuffle or apply a map function to the new sharded dataset, for example:
>>> dataset = dataset.shuffle(buffer_size=10000)
>>> dataset = dataset.batch(batch_size)
>>> dataset = dataset.repeat(num_epochs)
>>> # create the iterator for the dataset and the input tensor
>>> iterator = dataset.make_one_shot_iterator()
>>> next_element = iterator.get_next()
>>> with tf.device(task_spec.device_fn()):
>>> # next_element is the input for the graph
>>> tensors = create_graph(next_element)
>>> with tl.DistributedSession(task_spec=task_spec,
... checkpoint_dir='/tmp/ckpt') as session:
>>> while not session.should_stop():
>>> session.run(tensors)
References
----------
- `MonitoredTrainingSession <https://www.tensorflow.org/api_docs/python/tf/train/MonitoredTrainingSession>`__
"""
target = task_spec.target() if task_spec is not None else None
is_chief = task_spec.is_master() if task_spec is not None else True
return tf.train.MonitoredTrainingSession(
master=target, is_chief=is_chief, checkpoint_dir=checkpoint_dir, scaffold=scaffold,
save_checkpoint_secs=save_checkpoint_secs, save_summaries_steps=save_summaries_steps,
save_summaries_secs=save_summaries_secs, log_step_count_steps=log_step_count_steps,
stop_grace_period_secs=stop_grace_period_secs, config=config, hooks=hooks, chief_only_hooks=chief_only_hooks
) | [
"def",
"create_distributed_session",
"(",
"task_spec",
"=",
"None",
",",
"checkpoint_dir",
"=",
"None",
",",
"scaffold",
"=",
"None",
",",
"hooks",
"=",
"None",
",",
"chief_only_hooks",
"=",
"None",
",",
"save_checkpoint_secs",
"=",
"600",
",",
"save_summaries_steps",
"=",
"object",
"(",
")",
",",
"save_summaries_secs",
"=",
"object",
"(",
")",
",",
"config",
"=",
"None",
",",
"stop_grace_period_secs",
"=",
"120",
",",
"log_step_count_steps",
"=",
"100",
")",
":",
"target",
"=",
"task_spec",
".",
"target",
"(",
")",
"if",
"task_spec",
"is",
"not",
"None",
"else",
"None",
"is_chief",
"=",
"task_spec",
".",
"is_master",
"(",
")",
"if",
"task_spec",
"is",
"not",
"None",
"else",
"True",
"return",
"tf",
".",
"train",
".",
"MonitoredTrainingSession",
"(",
"master",
"=",
"target",
",",
"is_chief",
"=",
"is_chief",
",",
"checkpoint_dir",
"=",
"checkpoint_dir",
",",
"scaffold",
"=",
"scaffold",
",",
"save_checkpoint_secs",
"=",
"save_checkpoint_secs",
",",
"save_summaries_steps",
"=",
"save_summaries_steps",
",",
"save_summaries_secs",
"=",
"save_summaries_secs",
",",
"log_step_count_steps",
"=",
"log_step_count_steps",
",",
"stop_grace_period_secs",
"=",
"stop_grace_period_secs",
",",
"config",
"=",
"config",
",",
"hooks",
"=",
"hooks",
",",
"chief_only_hooks",
"=",
"chief_only_hooks",
")"
] | Creates a distributed session.
It calls `MonitoredTrainingSession` to create a :class:`MonitoredSession` for distributed training.
Parameters
----------
task_spec : :class:`TaskSpecDef`.
The task spec definition from create_task_spec_def()
checkpoint_dir : str.
Optional path to a directory where to restore variables.
scaffold : ``Scaffold``
A `Scaffold` used for gathering or building supportive ops.
If not specified, a default one is created. It's used to finalize the graph.
hooks : list of ``SessionRunHook`` objects.
Optional
chief_only_hooks : list of ``SessionRunHook`` objects.
Activate these hooks if `is_chief==True`, ignore otherwise.
save_checkpoint_secs : int
The frequency, in seconds, that a checkpoint is saved
using a default checkpoint saver. If `save_checkpoint_secs` is set to
`None`, then the default checkpoint saver isn't used.
save_summaries_steps : int
The frequency, in number of global steps, that the
summaries are written to disk using a default summary saver. If both
`save_summaries_steps` and `save_summaries_secs` are set to `None`, then
the default summary saver isn't used. Default 100.
save_summaries_secs : int
The frequency, in secs, that the summaries are written
to disk using a default summary saver. If both `save_summaries_steps` and
`save_summaries_secs` are set to `None`, then the default summary saver
isn't used. Default not enabled.
config : ``tf.ConfigProto``
an instance of `tf.ConfigProto` proto used to configure the session.
It's the `config` argument of constructor of `tf.Session`.
stop_grace_period_secs : int
Number of seconds given to threads to stop after
`close()` has been called.
log_step_count_steps : int
The frequency, in number of global steps, that the
global step/sec is logged.
Examples
--------
A simple example for distributed training where all the workers use the same dataset:
>>> task_spec = TaskSpec()
>>> with tf.device(task_spec.device_fn()):
>>> tensors = create_graph()
>>> with tl.DistributedSession(task_spec=task_spec,
... checkpoint_dir='/tmp/ckpt') as session:
>>> while not session.should_stop():
>>> session.run(tensors)
An example where the dataset is shared among the workers
(see https://www.tensorflow.org/programmers_guide/datasets):
>>> task_spec = TaskSpec()
>>> # dataset is a :class:`tf.data.Dataset` with the raw data
>>> dataset = create_dataset()
>>> if task_spec is not None:
>>> dataset = dataset.shard(task_spec.num_workers, task_spec.shard_index)
>>> # shuffle or apply a map function to the new sharded dataset, for example:
>>> dataset = dataset.shuffle(buffer_size=10000)
>>> dataset = dataset.batch(batch_size)
>>> dataset = dataset.repeat(num_epochs)
>>> # create the iterator for the dataset and the input tensor
>>> iterator = dataset.make_one_shot_iterator()
>>> next_element = iterator.get_next()
>>> with tf.device(task_spec.device_fn()):
>>> # next_element is the input for the graph
>>> tensors = create_graph(next_element)
>>> with tl.DistributedSession(task_spec=task_spec,
... checkpoint_dir='/tmp/ckpt') as session:
>>> while not session.should_stop():
>>> session.run(tensors)
References
----------
- `MonitoredTrainingSession <https://www.tensorflow.org/api_docs/python/tf/train/MonitoredTrainingSession>`__ | [
"Creates",
"a",
"distributed",
"session",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/distributed.py#L398-L491 | valid |
tensorlayer/tensorlayer | tensorlayer/distributed.py | Trainer.validation_metrics | def validation_metrics(self):
"""A helper function to compute validation related metrics"""
if (self._validation_iterator is None) or (self._validation_metrics is None):
raise AttributeError('Validation is not setup.')
n = 0.0
metric_sums = [0.0] * len(self._validation_metrics)
self._sess.run(self._validation_iterator.initializer)
while True:
try:
metrics = self._sess.run(self._validation_metrics)
for i, m in enumerate(metrics):
metric_sums[i] += m
n += 1.0
except tf.errors.OutOfRangeError:
break
for i, m in enumerate(metric_sums):
metric_sums[i] = metric_sums[i] / n
return zip(self._validation_metrics, metric_sums) | python | def validation_metrics(self):
"""A helper function to compute validation related metrics"""
if (self._validation_iterator is None) or (self._validation_metrics is None):
raise AttributeError('Validation is not setup.')
n = 0.0
metric_sums = [0.0] * len(self._validation_metrics)
self._sess.run(self._validation_iterator.initializer)
while True:
try:
metrics = self._sess.run(self._validation_metrics)
for i, m in enumerate(metrics):
metric_sums[i] += m
n += 1.0
except tf.errors.OutOfRangeError:
break
for i, m in enumerate(metric_sums):
metric_sums[i] = metric_sums[i] / n
return zip(self._validation_metrics, metric_sums) | [
"def",
"validation_metrics",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_validation_iterator",
"is",
"None",
")",
"or",
"(",
"self",
".",
"_validation_metrics",
"is",
"None",
")",
":",
"raise",
"AttributeError",
"(",
"'Validation is not setup.'",
")",
"n",
"=",
"0.0",
"metric_sums",
"=",
"[",
"0.0",
"]",
"*",
"len",
"(",
"self",
".",
"_validation_metrics",
")",
"self",
".",
"_sess",
".",
"run",
"(",
"self",
".",
"_validation_iterator",
".",
"initializer",
")",
"while",
"True",
":",
"try",
":",
"metrics",
"=",
"self",
".",
"_sess",
".",
"run",
"(",
"self",
".",
"_validation_metrics",
")",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"metrics",
")",
":",
"metric_sums",
"[",
"i",
"]",
"+=",
"m",
"n",
"+=",
"1.0",
"except",
"tf",
".",
"errors",
".",
"OutOfRangeError",
":",
"break",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"metric_sums",
")",
":",
"metric_sums",
"[",
"i",
"]",
"=",
"metric_sums",
"[",
"i",
"]",
"/",
"n",
"return",
"zip",
"(",
"self",
".",
"_validation_metrics",
",",
"metric_sums",
")"
] | A helper function to compute validation related metrics | [
"A",
"helper",
"function",
"to",
"compute",
"validation",
"related",
"metrics"
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/distributed.py#L187-L206 | valid |
tensorlayer/tensorlayer | tensorlayer/distributed.py | Trainer.train_and_validate_to_end | def train_and_validate_to_end(self, validate_step_size=50):
"""A helper function that shows how to train and validate a model at the same time.
Parameters
----------
validate_step_size : int
Validate the training network every N steps.
"""
while not self._sess.should_stop():
self.train_on_batch() # Run a training step synchronously.
if self.global_step % validate_step_size == 0:
# logging.info("Average loss for validation dataset: %s" % self.get_validation_metrics())
log_str = 'step: %d, ' % self.global_step
for n, m in self.validation_metrics:
log_str += '%s: %f, ' % (n.name, m)
logging.info(log_str) | python | def train_and_validate_to_end(self, validate_step_size=50):
"""A helper function that shows how to train and validate a model at the same time.
Parameters
----------
validate_step_size : int
Validate the training network every N steps.
"""
while not self._sess.should_stop():
self.train_on_batch() # Run a training step synchronously.
if self.global_step % validate_step_size == 0:
# logging.info("Average loss for validation dataset: %s" % self.get_validation_metrics())
log_str = 'step: %d, ' % self.global_step
for n, m in self.validation_metrics:
log_str += '%s: %f, ' % (n.name, m)
logging.info(log_str) | [
"def",
"train_and_validate_to_end",
"(",
"self",
",",
"validate_step_size",
"=",
"50",
")",
":",
"while",
"not",
"self",
".",
"_sess",
".",
"should_stop",
"(",
")",
":",
"self",
".",
"train_on_batch",
"(",
")",
"# Run a training step synchronously.",
"if",
"self",
".",
"global_step",
"%",
"validate_step_size",
"==",
"0",
":",
"# logging.info(\"Average loss for validation dataset: %s\" % self.get_validation_metrics())",
"log_str",
"=",
"'step: %d, '",
"%",
"self",
".",
"global_step",
"for",
"n",
",",
"m",
"in",
"self",
".",
"validation_metrics",
":",
"log_str",
"+=",
"'%s: %f, '",
"%",
"(",
"n",
".",
"name",
",",
"m",
")",
"logging",
".",
"info",
"(",
"log_str",
")"
] | A helper function that shows how to train and validate a model at the same time.
Parameters
----------
validate_step_size : int
Validate the training network every N steps. | [
"A",
"helper",
"function",
"that",
"shows",
"how",
"to",
"train",
"and",
"validate",
"a",
"model",
"at",
"the",
"same",
"time",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/distributed.py#L212-L228 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | _load_mnist_dataset | def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):
"""A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
The dataset name you want to use(the default is 'mnist').
url : str
The url of dataset(the default is 'http://yann.lecun.com/exdb/mnist/').
"""
path = os.path.join(path, name)
# Define functions for loading mnist-like data's images and labels.
# For convenience, they also download the requested files if needed.
def load_mnist_images(path, filename):
filepath = maybe_download_and_extract(filename, path, url)
logging.info(filepath)
# Read the inputs in Yann LeCun's binary format.
with gzip.open(filepath, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=16)
# The inputs are vectors now, we reshape them to monochrome 2D images,
# following the shape convention: (examples, channels, rows, columns)
data = data.reshape(shape)
# The inputs come as bytes, we convert them to float32 in range [0,1].
# (Actually to range [0, 255/256], for compatibility to the version
# provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)
return data / np.float32(256)
def load_mnist_labels(path, filename):
filepath = maybe_download_and_extract(filename, path, url)
# Read the labels in Yann LeCun's binary format.
with gzip.open(filepath, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=8)
# The labels are vectors of integers now, that's exactly what we want.
return data
# Download and read the training and test set images and labels.
logging.info("Load or Download {0} > {1}".format(name.upper(), path))
X_train = load_mnist_images(path, 'train-images-idx3-ubyte.gz')
y_train = load_mnist_labels(path, 'train-labels-idx1-ubyte.gz')
X_test = load_mnist_images(path, 't10k-images-idx3-ubyte.gz')
y_test = load_mnist_labels(path, 't10k-labels-idx1-ubyte.gz')
# We reserve the last 10000 training examples for validation.
X_train, X_val = X_train[:-10000], X_train[-10000:]
y_train, y_val = y_train[:-10000], y_train[-10000:]
# We just return all the arrays in order, as expected in main().
# (It doesn't matter how we do this as long as we can read them again.)
X_train = np.asarray(X_train, dtype=np.float32)
y_train = np.asarray(y_train, dtype=np.int32)
X_val = np.asarray(X_val, dtype=np.float32)
y_val = np.asarray(y_val, dtype=np.int32)
X_test = np.asarray(X_test, dtype=np.float32)
y_test = np.asarray(y_test, dtype=np.int32)
return X_train, y_train, X_val, y_val, X_test, y_test | python | def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):
"""A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
The dataset name you want to use(the default is 'mnist').
url : str
The url of dataset(the default is 'http://yann.lecun.com/exdb/mnist/').
"""
path = os.path.join(path, name)
# Define functions for loading mnist-like data's images and labels.
# For convenience, they also download the requested files if needed.
def load_mnist_images(path, filename):
filepath = maybe_download_and_extract(filename, path, url)
logging.info(filepath)
# Read the inputs in Yann LeCun's binary format.
with gzip.open(filepath, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=16)
# The inputs are vectors now, we reshape them to monochrome 2D images,
# following the shape convention: (examples, channels, rows, columns)
data = data.reshape(shape)
# The inputs come as bytes, we convert them to float32 in range [0,1].
# (Actually to range [0, 255/256], for compatibility to the version
# provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)
return data / np.float32(256)
def load_mnist_labels(path, filename):
filepath = maybe_download_and_extract(filename, path, url)
# Read the labels in Yann LeCun's binary format.
with gzip.open(filepath, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=8)
# The labels are vectors of integers now, that's exactly what we want.
return data
# Download and read the training and test set images and labels.
logging.info("Load or Download {0} > {1}".format(name.upper(), path))
X_train = load_mnist_images(path, 'train-images-idx3-ubyte.gz')
y_train = load_mnist_labels(path, 'train-labels-idx1-ubyte.gz')
X_test = load_mnist_images(path, 't10k-images-idx3-ubyte.gz')
y_test = load_mnist_labels(path, 't10k-labels-idx1-ubyte.gz')
# We reserve the last 10000 training examples for validation.
X_train, X_val = X_train[:-10000], X_train[-10000:]
y_train, y_val = y_train[:-10000], y_train[-10000:]
# We just return all the arrays in order, as expected in main().
# (It doesn't matter how we do this as long as we can read them again.)
X_train = np.asarray(X_train, dtype=np.float32)
y_train = np.asarray(y_train, dtype=np.int32)
X_val = np.asarray(X_val, dtype=np.float32)
y_val = np.asarray(y_val, dtype=np.int32)
X_test = np.asarray(X_test, dtype=np.float32)
y_test = np.asarray(y_test, dtype=np.int32)
return X_train, y_train, X_val, y_val, X_test, y_test | [
"def",
"_load_mnist_dataset",
"(",
"shape",
",",
"path",
",",
"name",
"=",
"'mnist'",
",",
"url",
"=",
"'http://yann.lecun.com/exdb/mnist/'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"# Define functions for loading mnist-like data's images and labels.",
"# For convenience, they also download the requested files if needed.",
"def",
"load_mnist_images",
"(",
"path",
",",
"filename",
")",
":",
"filepath",
"=",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
")",
"logging",
".",
"info",
"(",
"filepath",
")",
"# Read the inputs in Yann LeCun's binary format.",
"with",
"gzip",
".",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"np",
".",
"frombuffer",
"(",
"f",
".",
"read",
"(",
")",
",",
"np",
".",
"uint8",
",",
"offset",
"=",
"16",
")",
"# The inputs are vectors now, we reshape them to monochrome 2D images,",
"# following the shape convention: (examples, channels, rows, columns)",
"data",
"=",
"data",
".",
"reshape",
"(",
"shape",
")",
"# The inputs come as bytes, we convert them to float32 in range [0,1].",
"# (Actually to range [0, 255/256], for compatibility to the version",
"# provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)",
"return",
"data",
"/",
"np",
".",
"float32",
"(",
"256",
")",
"def",
"load_mnist_labels",
"(",
"path",
",",
"filename",
")",
":",
"filepath",
"=",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
")",
"# Read the labels in Yann LeCun's binary format.",
"with",
"gzip",
".",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"np",
".",
"frombuffer",
"(",
"f",
".",
"read",
"(",
")",
",",
"np",
".",
"uint8",
",",
"offset",
"=",
"8",
")",
"# The labels are vectors of integers now, that's exactly what we want.",
"return",
"data",
"# Download and read the training and test set images and labels.",
"logging",
".",
"info",
"(",
"\"Load or Download {0} > {1}\"",
".",
"format",
"(",
"name",
".",
"upper",
"(",
")",
",",
"path",
")",
")",
"X_train",
"=",
"load_mnist_images",
"(",
"path",
",",
"'train-images-idx3-ubyte.gz'",
")",
"y_train",
"=",
"load_mnist_labels",
"(",
"path",
",",
"'train-labels-idx1-ubyte.gz'",
")",
"X_test",
"=",
"load_mnist_images",
"(",
"path",
",",
"'t10k-images-idx3-ubyte.gz'",
")",
"y_test",
"=",
"load_mnist_labels",
"(",
"path",
",",
"'t10k-labels-idx1-ubyte.gz'",
")",
"# We reserve the last 10000 training examples for validation.",
"X_train",
",",
"X_val",
"=",
"X_train",
"[",
":",
"-",
"10000",
"]",
",",
"X_train",
"[",
"-",
"10000",
":",
"]",
"y_train",
",",
"y_val",
"=",
"y_train",
"[",
":",
"-",
"10000",
"]",
",",
"y_train",
"[",
"-",
"10000",
":",
"]",
"# We just return all the arrays in order, as expected in main().",
"# (It doesn't matter how we do this as long as we can read them again.)",
"X_train",
"=",
"np",
".",
"asarray",
"(",
"X_train",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"y_train",
"=",
"np",
".",
"asarray",
"(",
"y_train",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"X_val",
"=",
"np",
".",
"asarray",
"(",
"X_val",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"y_val",
"=",
"np",
".",
"asarray",
"(",
"y_val",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"X_test",
"=",
"np",
".",
"asarray",
"(",
"X_test",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"y_test",
"=",
"np",
".",
"asarray",
"(",
"y_test",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"return",
"X_train",
",",
"y_train",
",",
"X_val",
",",
"y_val",
",",
"X_test",
",",
"y_test"
] | A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
The dataset name you want to use(the default is 'mnist').
url : str
The url of dataset(the default is 'http://yann.lecun.com/exdb/mnist/'). | [
"A",
"generic",
"function",
"to",
"load",
"mnist",
"-",
"like",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L135-L195 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_cifar10_dataset | def load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data', plotable=False):
"""Load CIFAR-10 dataset.
It consists of 60000 32x32 colour images in 10 classes, with
6000 images per class. There are 50000 training images and 10000 test images.
The dataset is divided into five training batches and one test batch, each with
10000 images. The test batch contains exactly 1000 randomly-selected images from
each class. The training batches contain the remaining images in random order,
but some training batches may contain more images from one class than another.
Between them, the training batches contain exactly 5000 images from each class.
Parameters
----------
shape : tupe
The shape of digit images e.g. (-1, 3, 32, 32) and (-1, 32, 32, 3).
path : str
The path that the data is downloaded to, defaults is ``data/cifar10/``.
plotable : boolean
Whether to plot some image examples, False as default.
Examples
--------
>>> X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
References
----------
- `CIFAR website <https://www.cs.toronto.edu/~kriz/cifar.html>`__
- `Data download link <https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz>`__
- `<https://teratail.com/questions/28932>`__
"""
path = os.path.join(path, 'cifar10')
logging.info("Load or Download cifar10 > {}".format(path))
# Helper function to unpickle the data
def unpickle(file):
fp = open(file, 'rb')
if sys.version_info.major == 2:
data = pickle.load(fp)
elif sys.version_info.major == 3:
data = pickle.load(fp, encoding='latin-1')
fp.close()
return data
filename = 'cifar-10-python.tar.gz'
url = 'https://www.cs.toronto.edu/~kriz/'
# Download and uncompress file
maybe_download_and_extract(filename, path, url, extract=True)
# Unpickle file and fill in data
X_train = None
y_train = []
for i in range(1, 6):
data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "data_batch_{}".format(i)))
if i == 1:
X_train = data_dic['data']
else:
X_train = np.vstack((X_train, data_dic['data']))
y_train += data_dic['labels']
test_data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "test_batch"))
X_test = test_data_dic['data']
y_test = np.array(test_data_dic['labels'])
if shape == (-1, 3, 32, 32):
X_test = X_test.reshape(shape)
X_train = X_train.reshape(shape)
elif shape == (-1, 32, 32, 3):
X_test = X_test.reshape(shape, order='F')
X_train = X_train.reshape(shape, order='F')
X_test = np.transpose(X_test, (0, 2, 1, 3))
X_train = np.transpose(X_train, (0, 2, 1, 3))
else:
X_test = X_test.reshape(shape)
X_train = X_train.reshape(shape)
y_train = np.array(y_train)
if plotable:
logging.info('\nCIFAR-10')
fig = plt.figure(1)
logging.info('Shape of a training image: X_train[0] %s' % X_train[0].shape)
plt.ion() # interactive mode
count = 1
for _ in range(10): # each row
for _ in range(10): # each column
_ = fig.add_subplot(10, 10, count)
if shape == (-1, 3, 32, 32):
# plt.imshow(X_train[count-1], interpolation='nearest')
plt.imshow(np.transpose(X_train[count - 1], (1, 2, 0)), interpolation='nearest')
# plt.imshow(np.transpose(X_train[count-1], (2, 1, 0)), interpolation='nearest')
elif shape == (-1, 32, 32, 3):
plt.imshow(X_train[count - 1], interpolation='nearest')
# plt.imshow(np.transpose(X_train[count-1], (1, 0, 2)), interpolation='nearest')
else:
raise Exception("Do not support the given 'shape' to plot the image examples")
plt.gca().xaxis.set_major_locator(plt.NullLocator()) # 不显示刻度(tick)
plt.gca().yaxis.set_major_locator(plt.NullLocator())
count = count + 1
plt.draw() # interactive mode
plt.pause(3) # interactive mode
logging.info("X_train: %s" % X_train.shape)
logging.info("y_train: %s" % y_train.shape)
logging.info("X_test: %s" % X_test.shape)
logging.info("y_test: %s" % y_test.shape)
X_train = np.asarray(X_train, dtype=np.float32)
X_test = np.asarray(X_test, dtype=np.float32)
y_train = np.asarray(y_train, dtype=np.int32)
y_test = np.asarray(y_test, dtype=np.int32)
return X_train, y_train, X_test, y_test | python | def load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data', plotable=False):
"""Load CIFAR-10 dataset.
It consists of 60000 32x32 colour images in 10 classes, with
6000 images per class. There are 50000 training images and 10000 test images.
The dataset is divided into five training batches and one test batch, each with
10000 images. The test batch contains exactly 1000 randomly-selected images from
each class. The training batches contain the remaining images in random order,
but some training batches may contain more images from one class than another.
Between them, the training batches contain exactly 5000 images from each class.
Parameters
----------
shape : tupe
The shape of digit images e.g. (-1, 3, 32, 32) and (-1, 32, 32, 3).
path : str
The path that the data is downloaded to, defaults is ``data/cifar10/``.
plotable : boolean
Whether to plot some image examples, False as default.
Examples
--------
>>> X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
References
----------
- `CIFAR website <https://www.cs.toronto.edu/~kriz/cifar.html>`__
- `Data download link <https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz>`__
- `<https://teratail.com/questions/28932>`__
"""
path = os.path.join(path, 'cifar10')
logging.info("Load or Download cifar10 > {}".format(path))
# Helper function to unpickle the data
def unpickle(file):
fp = open(file, 'rb')
if sys.version_info.major == 2:
data = pickle.load(fp)
elif sys.version_info.major == 3:
data = pickle.load(fp, encoding='latin-1')
fp.close()
return data
filename = 'cifar-10-python.tar.gz'
url = 'https://www.cs.toronto.edu/~kriz/'
# Download and uncompress file
maybe_download_and_extract(filename, path, url, extract=True)
# Unpickle file and fill in data
X_train = None
y_train = []
for i in range(1, 6):
data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "data_batch_{}".format(i)))
if i == 1:
X_train = data_dic['data']
else:
X_train = np.vstack((X_train, data_dic['data']))
y_train += data_dic['labels']
test_data_dic = unpickle(os.path.join(path, 'cifar-10-batches-py/', "test_batch"))
X_test = test_data_dic['data']
y_test = np.array(test_data_dic['labels'])
if shape == (-1, 3, 32, 32):
X_test = X_test.reshape(shape)
X_train = X_train.reshape(shape)
elif shape == (-1, 32, 32, 3):
X_test = X_test.reshape(shape, order='F')
X_train = X_train.reshape(shape, order='F')
X_test = np.transpose(X_test, (0, 2, 1, 3))
X_train = np.transpose(X_train, (0, 2, 1, 3))
else:
X_test = X_test.reshape(shape)
X_train = X_train.reshape(shape)
y_train = np.array(y_train)
if plotable:
logging.info('\nCIFAR-10')
fig = plt.figure(1)
logging.info('Shape of a training image: X_train[0] %s' % X_train[0].shape)
plt.ion() # interactive mode
count = 1
for _ in range(10): # each row
for _ in range(10): # each column
_ = fig.add_subplot(10, 10, count)
if shape == (-1, 3, 32, 32):
# plt.imshow(X_train[count-1], interpolation='nearest')
plt.imshow(np.transpose(X_train[count - 1], (1, 2, 0)), interpolation='nearest')
# plt.imshow(np.transpose(X_train[count-1], (2, 1, 0)), interpolation='nearest')
elif shape == (-1, 32, 32, 3):
plt.imshow(X_train[count - 1], interpolation='nearest')
# plt.imshow(np.transpose(X_train[count-1], (1, 0, 2)), interpolation='nearest')
else:
raise Exception("Do not support the given 'shape' to plot the image examples")
plt.gca().xaxis.set_major_locator(plt.NullLocator()) # 不显示刻度(tick)
plt.gca().yaxis.set_major_locator(plt.NullLocator())
count = count + 1
plt.draw() # interactive mode
plt.pause(3) # interactive mode
logging.info("X_train: %s" % X_train.shape)
logging.info("y_train: %s" % y_train.shape)
logging.info("X_test: %s" % X_test.shape)
logging.info("y_test: %s" % y_test.shape)
X_train = np.asarray(X_train, dtype=np.float32)
X_test = np.asarray(X_test, dtype=np.float32)
y_train = np.asarray(y_train, dtype=np.int32)
y_test = np.asarray(y_test, dtype=np.int32)
return X_train, y_train, X_test, y_test | [
"def",
"load_cifar10_dataset",
"(",
"shape",
"=",
"(",
"-",
"1",
",",
"32",
",",
"32",
",",
"3",
")",
",",
"path",
"=",
"'data'",
",",
"plotable",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'cifar10'",
")",
"logging",
".",
"info",
"(",
"\"Load or Download cifar10 > {}\"",
".",
"format",
"(",
"path",
")",
")",
"# Helper function to unpickle the data",
"def",
"unpickle",
"(",
"file",
")",
":",
"fp",
"=",
"open",
"(",
"file",
",",
"'rb'",
")",
"if",
"sys",
".",
"version_info",
".",
"major",
"==",
"2",
":",
"data",
"=",
"pickle",
".",
"load",
"(",
"fp",
")",
"elif",
"sys",
".",
"version_info",
".",
"major",
"==",
"3",
":",
"data",
"=",
"pickle",
".",
"load",
"(",
"fp",
",",
"encoding",
"=",
"'latin-1'",
")",
"fp",
".",
"close",
"(",
")",
"return",
"data",
"filename",
"=",
"'cifar-10-python.tar.gz'",
"url",
"=",
"'https://www.cs.toronto.edu/~kriz/'",
"# Download and uncompress file",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
",",
"extract",
"=",
"True",
")",
"# Unpickle file and fill in data",
"X_train",
"=",
"None",
"y_train",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"6",
")",
":",
"data_dic",
"=",
"unpickle",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'cifar-10-batches-py/'",
",",
"\"data_batch_{}\"",
".",
"format",
"(",
"i",
")",
")",
")",
"if",
"i",
"==",
"1",
":",
"X_train",
"=",
"data_dic",
"[",
"'data'",
"]",
"else",
":",
"X_train",
"=",
"np",
".",
"vstack",
"(",
"(",
"X_train",
",",
"data_dic",
"[",
"'data'",
"]",
")",
")",
"y_train",
"+=",
"data_dic",
"[",
"'labels'",
"]",
"test_data_dic",
"=",
"unpickle",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'cifar-10-batches-py/'",
",",
"\"test_batch\"",
")",
")",
"X_test",
"=",
"test_data_dic",
"[",
"'data'",
"]",
"y_test",
"=",
"np",
".",
"array",
"(",
"test_data_dic",
"[",
"'labels'",
"]",
")",
"if",
"shape",
"==",
"(",
"-",
"1",
",",
"3",
",",
"32",
",",
"32",
")",
":",
"X_test",
"=",
"X_test",
".",
"reshape",
"(",
"shape",
")",
"X_train",
"=",
"X_train",
".",
"reshape",
"(",
"shape",
")",
"elif",
"shape",
"==",
"(",
"-",
"1",
",",
"32",
",",
"32",
",",
"3",
")",
":",
"X_test",
"=",
"X_test",
".",
"reshape",
"(",
"shape",
",",
"order",
"=",
"'F'",
")",
"X_train",
"=",
"X_train",
".",
"reshape",
"(",
"shape",
",",
"order",
"=",
"'F'",
")",
"X_test",
"=",
"np",
".",
"transpose",
"(",
"X_test",
",",
"(",
"0",
",",
"2",
",",
"1",
",",
"3",
")",
")",
"X_train",
"=",
"np",
".",
"transpose",
"(",
"X_train",
",",
"(",
"0",
",",
"2",
",",
"1",
",",
"3",
")",
")",
"else",
":",
"X_test",
"=",
"X_test",
".",
"reshape",
"(",
"shape",
")",
"X_train",
"=",
"X_train",
".",
"reshape",
"(",
"shape",
")",
"y_train",
"=",
"np",
".",
"array",
"(",
"y_train",
")",
"if",
"plotable",
":",
"logging",
".",
"info",
"(",
"'\\nCIFAR-10'",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
"1",
")",
"logging",
".",
"info",
"(",
"'Shape of a training image: X_train[0] %s'",
"%",
"X_train",
"[",
"0",
"]",
".",
"shape",
")",
"plt",
".",
"ion",
"(",
")",
"# interactive mode",
"count",
"=",
"1",
"for",
"_",
"in",
"range",
"(",
"10",
")",
":",
"# each row",
"for",
"_",
"in",
"range",
"(",
"10",
")",
":",
"# each column",
"_",
"=",
"fig",
".",
"add_subplot",
"(",
"10",
",",
"10",
",",
"count",
")",
"if",
"shape",
"==",
"(",
"-",
"1",
",",
"3",
",",
"32",
",",
"32",
")",
":",
"# plt.imshow(X_train[count-1], interpolation='nearest')",
"plt",
".",
"imshow",
"(",
"np",
".",
"transpose",
"(",
"X_train",
"[",
"count",
"-",
"1",
"]",
",",
"(",
"1",
",",
"2",
",",
"0",
")",
")",
",",
"interpolation",
"=",
"'nearest'",
")",
"# plt.imshow(np.transpose(X_train[count-1], (2, 1, 0)), interpolation='nearest')",
"elif",
"shape",
"==",
"(",
"-",
"1",
",",
"32",
",",
"32",
",",
"3",
")",
":",
"plt",
".",
"imshow",
"(",
"X_train",
"[",
"count",
"-",
"1",
"]",
",",
"interpolation",
"=",
"'nearest'",
")",
"# plt.imshow(np.transpose(X_train[count-1], (1, 0, 2)), interpolation='nearest')",
"else",
":",
"raise",
"Exception",
"(",
"\"Do not support the given 'shape' to plot the image examples\"",
")",
"plt",
".",
"gca",
"(",
")",
".",
"xaxis",
".",
"set_major_locator",
"(",
"plt",
".",
"NullLocator",
"(",
")",
")",
"# 不显示刻度(tick)",
"plt",
".",
"gca",
"(",
")",
".",
"yaxis",
".",
"set_major_locator",
"(",
"plt",
".",
"NullLocator",
"(",
")",
")",
"count",
"=",
"count",
"+",
"1",
"plt",
".",
"draw",
"(",
")",
"# interactive mode",
"plt",
".",
"pause",
"(",
"3",
")",
"# interactive mode",
"logging",
".",
"info",
"(",
"\"X_train: %s\"",
"%",
"X_train",
".",
"shape",
")",
"logging",
".",
"info",
"(",
"\"y_train: %s\"",
"%",
"y_train",
".",
"shape",
")",
"logging",
".",
"info",
"(",
"\"X_test: %s\"",
"%",
"X_test",
".",
"shape",
")",
"logging",
".",
"info",
"(",
"\"y_test: %s\"",
"%",
"y_test",
".",
"shape",
")",
"X_train",
"=",
"np",
".",
"asarray",
"(",
"X_train",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"X_test",
"=",
"np",
".",
"asarray",
"(",
"X_test",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"y_train",
"=",
"np",
".",
"asarray",
"(",
"y_train",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"y_test",
"=",
"np",
".",
"asarray",
"(",
"y_test",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"return",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test"
] | Load CIFAR-10 dataset.
It consists of 60000 32x32 colour images in 10 classes, with
6000 images per class. There are 50000 training images and 10000 test images.
The dataset is divided into five training batches and one test batch, each with
10000 images. The test batch contains exactly 1000 randomly-selected images from
each class. The training batches contain the remaining images in random order,
but some training batches may contain more images from one class than another.
Between them, the training batches contain exactly 5000 images from each class.
Parameters
----------
shape : tupe
The shape of digit images e.g. (-1, 3, 32, 32) and (-1, 32, 32, 3).
path : str
The path that the data is downloaded to, defaults is ``data/cifar10/``.
plotable : boolean
Whether to plot some image examples, False as default.
Examples
--------
>>> X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
References
----------
- `CIFAR website <https://www.cs.toronto.edu/~kriz/cifar.html>`__
- `Data download link <https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz>`__
- `<https://teratail.com/questions/28932>`__ | [
"Load",
"CIFAR",
"-",
"10",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L198-L313 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_cropped_svhn | def load_cropped_svhn(path='data', include_extra=True):
"""Load Cropped SVHN.
The Cropped Street View House Numbers (SVHN) Dataset contains 32x32x3 RGB images.
Digit '1' has label 1, '9' has label 9 and '0' has label 0 (the original dataset uses 10 to represent '0'), see `ufldl website <http://ufldl.stanford.edu/housenumbers/>`__.
Parameters
----------
path : str
The path that the data is downloaded to.
include_extra : boolean
If True (default), add extra images to the training set.
Returns
-------
X_train, y_train, X_test, y_test: tuple
Return splitted training/test set respectively.
Examples
---------
>>> X_train, y_train, X_test, y_test = tl.files.load_cropped_svhn(include_extra=False)
>>> tl.vis.save_images(X_train[0:100], [10, 10], 'svhn.png')
"""
start_time = time.time()
path = os.path.join(path, 'cropped_svhn')
logging.info("Load or Download Cropped SVHN > {} | include extra images: {}".format(path, include_extra))
url = "http://ufldl.stanford.edu/housenumbers/"
np_file = os.path.join(path, "train_32x32.npz")
if file_exists(np_file) is False:
filename = "train_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_train = mat['X'] / 255.0 # to [0, 1]
X_train = np.transpose(X_train, (3, 0, 1, 2))
y_train = np.squeeze(mat['y'], axis=1)
y_train[y_train == 10] = 0 # replace 10 to 0
np.savez(np_file, X=X_train, y=y_train)
del_file(filepath)
else:
v = np.load(np_file)
X_train = v['X']
y_train = v['y']
logging.info(" n_train: {}".format(len(y_train)))
np_file = os.path.join(path, "test_32x32.npz")
if file_exists(np_file) is False:
filename = "test_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_test = mat['X'] / 255.0
X_test = np.transpose(X_test, (3, 0, 1, 2))
y_test = np.squeeze(mat['y'], axis=1)
y_test[y_test == 10] = 0
np.savez(np_file, X=X_test, y=y_test)
del_file(filepath)
else:
v = np.load(np_file)
X_test = v['X']
y_test = v['y']
logging.info(" n_test: {}".format(len(y_test)))
if include_extra:
logging.info(" getting extra 531131 images, please wait ...")
np_file = os.path.join(path, "extra_32x32.npz")
if file_exists(np_file) is False:
logging.info(" the first time to load extra images will take long time to convert the file format ...")
filename = "extra_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_extra = mat['X'] / 255.0
X_extra = np.transpose(X_extra, (3, 0, 1, 2))
y_extra = np.squeeze(mat['y'], axis=1)
y_extra[y_extra == 10] = 0
np.savez(np_file, X=X_extra, y=y_extra)
del_file(filepath)
else:
v = np.load(np_file)
X_extra = v['X']
y_extra = v['y']
# print(X_train.shape, X_extra.shape)
logging.info(" adding n_extra {} to n_train {}".format(len(y_extra), len(y_train)))
t = time.time()
X_train = np.concatenate((X_train, X_extra), 0)
y_train = np.concatenate((y_train, y_extra), 0)
# X_train = np.append(X_train, X_extra, axis=0)
# y_train = np.append(y_train, y_extra, axis=0)
logging.info(" added n_extra {} to n_train {} took {}s".format(len(y_extra), len(y_train), time.time() - t))
else:
logging.info(" no extra images are included")
logging.info(" image size: %s n_train: %d n_test: %d" % (str(X_train.shape[1:4]), len(y_train), len(y_test)))
logging.info(" took: {}s".format(int(time.time() - start_time)))
return X_train, y_train, X_test, y_test | python | def load_cropped_svhn(path='data', include_extra=True):
"""Load Cropped SVHN.
The Cropped Street View House Numbers (SVHN) Dataset contains 32x32x3 RGB images.
Digit '1' has label 1, '9' has label 9 and '0' has label 0 (the original dataset uses 10 to represent '0'), see `ufldl website <http://ufldl.stanford.edu/housenumbers/>`__.
Parameters
----------
path : str
The path that the data is downloaded to.
include_extra : boolean
If True (default), add extra images to the training set.
Returns
-------
X_train, y_train, X_test, y_test: tuple
Return splitted training/test set respectively.
Examples
---------
>>> X_train, y_train, X_test, y_test = tl.files.load_cropped_svhn(include_extra=False)
>>> tl.vis.save_images(X_train[0:100], [10, 10], 'svhn.png')
"""
start_time = time.time()
path = os.path.join(path, 'cropped_svhn')
logging.info("Load or Download Cropped SVHN > {} | include extra images: {}".format(path, include_extra))
url = "http://ufldl.stanford.edu/housenumbers/"
np_file = os.path.join(path, "train_32x32.npz")
if file_exists(np_file) is False:
filename = "train_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_train = mat['X'] / 255.0 # to [0, 1]
X_train = np.transpose(X_train, (3, 0, 1, 2))
y_train = np.squeeze(mat['y'], axis=1)
y_train[y_train == 10] = 0 # replace 10 to 0
np.savez(np_file, X=X_train, y=y_train)
del_file(filepath)
else:
v = np.load(np_file)
X_train = v['X']
y_train = v['y']
logging.info(" n_train: {}".format(len(y_train)))
np_file = os.path.join(path, "test_32x32.npz")
if file_exists(np_file) is False:
filename = "test_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_test = mat['X'] / 255.0
X_test = np.transpose(X_test, (3, 0, 1, 2))
y_test = np.squeeze(mat['y'], axis=1)
y_test[y_test == 10] = 0
np.savez(np_file, X=X_test, y=y_test)
del_file(filepath)
else:
v = np.load(np_file)
X_test = v['X']
y_test = v['y']
logging.info(" n_test: {}".format(len(y_test)))
if include_extra:
logging.info(" getting extra 531131 images, please wait ...")
np_file = os.path.join(path, "extra_32x32.npz")
if file_exists(np_file) is False:
logging.info(" the first time to load extra images will take long time to convert the file format ...")
filename = "extra_32x32.mat"
filepath = maybe_download_and_extract(filename, path, url)
mat = sio.loadmat(filepath)
X_extra = mat['X'] / 255.0
X_extra = np.transpose(X_extra, (3, 0, 1, 2))
y_extra = np.squeeze(mat['y'], axis=1)
y_extra[y_extra == 10] = 0
np.savez(np_file, X=X_extra, y=y_extra)
del_file(filepath)
else:
v = np.load(np_file)
X_extra = v['X']
y_extra = v['y']
# print(X_train.shape, X_extra.shape)
logging.info(" adding n_extra {} to n_train {}".format(len(y_extra), len(y_train)))
t = time.time()
X_train = np.concatenate((X_train, X_extra), 0)
y_train = np.concatenate((y_train, y_extra), 0)
# X_train = np.append(X_train, X_extra, axis=0)
# y_train = np.append(y_train, y_extra, axis=0)
logging.info(" added n_extra {} to n_train {} took {}s".format(len(y_extra), len(y_train), time.time() - t))
else:
logging.info(" no extra images are included")
logging.info(" image size: %s n_train: %d n_test: %d" % (str(X_train.shape[1:4]), len(y_train), len(y_test)))
logging.info(" took: {}s".format(int(time.time() - start_time)))
return X_train, y_train, X_test, y_test | [
"def",
"load_cropped_svhn",
"(",
"path",
"=",
"'data'",
",",
"include_extra",
"=",
"True",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'cropped_svhn'",
")",
"logging",
".",
"info",
"(",
"\"Load or Download Cropped SVHN > {} | include extra images: {}\"",
".",
"format",
"(",
"path",
",",
"include_extra",
")",
")",
"url",
"=",
"\"http://ufldl.stanford.edu/housenumbers/\"",
"np_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"train_32x32.npz\"",
")",
"if",
"file_exists",
"(",
"np_file",
")",
"is",
"False",
":",
"filename",
"=",
"\"train_32x32.mat\"",
"filepath",
"=",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
")",
"mat",
"=",
"sio",
".",
"loadmat",
"(",
"filepath",
")",
"X_train",
"=",
"mat",
"[",
"'X'",
"]",
"/",
"255.0",
"# to [0, 1]",
"X_train",
"=",
"np",
".",
"transpose",
"(",
"X_train",
",",
"(",
"3",
",",
"0",
",",
"1",
",",
"2",
")",
")",
"y_train",
"=",
"np",
".",
"squeeze",
"(",
"mat",
"[",
"'y'",
"]",
",",
"axis",
"=",
"1",
")",
"y_train",
"[",
"y_train",
"==",
"10",
"]",
"=",
"0",
"# replace 10 to 0",
"np",
".",
"savez",
"(",
"np_file",
",",
"X",
"=",
"X_train",
",",
"y",
"=",
"y_train",
")",
"del_file",
"(",
"filepath",
")",
"else",
":",
"v",
"=",
"np",
".",
"load",
"(",
"np_file",
")",
"X_train",
"=",
"v",
"[",
"'X'",
"]",
"y_train",
"=",
"v",
"[",
"'y'",
"]",
"logging",
".",
"info",
"(",
"\" n_train: {}\"",
".",
"format",
"(",
"len",
"(",
"y_train",
")",
")",
")",
"np_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"test_32x32.npz\"",
")",
"if",
"file_exists",
"(",
"np_file",
")",
"is",
"False",
":",
"filename",
"=",
"\"test_32x32.mat\"",
"filepath",
"=",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
")",
"mat",
"=",
"sio",
".",
"loadmat",
"(",
"filepath",
")",
"X_test",
"=",
"mat",
"[",
"'X'",
"]",
"/",
"255.0",
"X_test",
"=",
"np",
".",
"transpose",
"(",
"X_test",
",",
"(",
"3",
",",
"0",
",",
"1",
",",
"2",
")",
")",
"y_test",
"=",
"np",
".",
"squeeze",
"(",
"mat",
"[",
"'y'",
"]",
",",
"axis",
"=",
"1",
")",
"y_test",
"[",
"y_test",
"==",
"10",
"]",
"=",
"0",
"np",
".",
"savez",
"(",
"np_file",
",",
"X",
"=",
"X_test",
",",
"y",
"=",
"y_test",
")",
"del_file",
"(",
"filepath",
")",
"else",
":",
"v",
"=",
"np",
".",
"load",
"(",
"np_file",
")",
"X_test",
"=",
"v",
"[",
"'X'",
"]",
"y_test",
"=",
"v",
"[",
"'y'",
"]",
"logging",
".",
"info",
"(",
"\" n_test: {}\"",
".",
"format",
"(",
"len",
"(",
"y_test",
")",
")",
")",
"if",
"include_extra",
":",
"logging",
".",
"info",
"(",
"\" getting extra 531131 images, please wait ...\"",
")",
"np_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"extra_32x32.npz\"",
")",
"if",
"file_exists",
"(",
"np_file",
")",
"is",
"False",
":",
"logging",
".",
"info",
"(",
"\" the first time to load extra images will take long time to convert the file format ...\"",
")",
"filename",
"=",
"\"extra_32x32.mat\"",
"filepath",
"=",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
")",
"mat",
"=",
"sio",
".",
"loadmat",
"(",
"filepath",
")",
"X_extra",
"=",
"mat",
"[",
"'X'",
"]",
"/",
"255.0",
"X_extra",
"=",
"np",
".",
"transpose",
"(",
"X_extra",
",",
"(",
"3",
",",
"0",
",",
"1",
",",
"2",
")",
")",
"y_extra",
"=",
"np",
".",
"squeeze",
"(",
"mat",
"[",
"'y'",
"]",
",",
"axis",
"=",
"1",
")",
"y_extra",
"[",
"y_extra",
"==",
"10",
"]",
"=",
"0",
"np",
".",
"savez",
"(",
"np_file",
",",
"X",
"=",
"X_extra",
",",
"y",
"=",
"y_extra",
")",
"del_file",
"(",
"filepath",
")",
"else",
":",
"v",
"=",
"np",
".",
"load",
"(",
"np_file",
")",
"X_extra",
"=",
"v",
"[",
"'X'",
"]",
"y_extra",
"=",
"v",
"[",
"'y'",
"]",
"# print(X_train.shape, X_extra.shape)",
"logging",
".",
"info",
"(",
"\" adding n_extra {} to n_train {}\"",
".",
"format",
"(",
"len",
"(",
"y_extra",
")",
",",
"len",
"(",
"y_train",
")",
")",
")",
"t",
"=",
"time",
".",
"time",
"(",
")",
"X_train",
"=",
"np",
".",
"concatenate",
"(",
"(",
"X_train",
",",
"X_extra",
")",
",",
"0",
")",
"y_train",
"=",
"np",
".",
"concatenate",
"(",
"(",
"y_train",
",",
"y_extra",
")",
",",
"0",
")",
"# X_train = np.append(X_train, X_extra, axis=0)",
"# y_train = np.append(y_train, y_extra, axis=0)",
"logging",
".",
"info",
"(",
"\" added n_extra {} to n_train {} took {}s\"",
".",
"format",
"(",
"len",
"(",
"y_extra",
")",
",",
"len",
"(",
"y_train",
")",
",",
"time",
".",
"time",
"(",
")",
"-",
"t",
")",
")",
"else",
":",
"logging",
".",
"info",
"(",
"\" no extra images are included\"",
")",
"logging",
".",
"info",
"(",
"\" image size: %s n_train: %d n_test: %d\"",
"%",
"(",
"str",
"(",
"X_train",
".",
"shape",
"[",
"1",
":",
"4",
"]",
")",
",",
"len",
"(",
"y_train",
")",
",",
"len",
"(",
"y_test",
")",
")",
")",
"logging",
".",
"info",
"(",
"\" took: {}s\"",
".",
"format",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
")",
")",
"return",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test"
] | Load Cropped SVHN.
The Cropped Street View House Numbers (SVHN) Dataset contains 32x32x3 RGB images.
Digit '1' has label 1, '9' has label 9 and '0' has label 0 (the original dataset uses 10 to represent '0'), see `ufldl website <http://ufldl.stanford.edu/housenumbers/>`__.
Parameters
----------
path : str
The path that the data is downloaded to.
include_extra : boolean
If True (default), add extra images to the training set.
Returns
-------
X_train, y_train, X_test, y_test: tuple
Return splitted training/test set respectively.
Examples
---------
>>> X_train, y_train, X_test, y_test = tl.files.load_cropped_svhn(include_extra=False)
>>> tl.vis.save_images(X_train[0:100], [10, 10], 'svhn.png') | [
"Load",
"Cropped",
"SVHN",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L316-L410 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_ptb_dataset | def load_ptb_dataset(path='data'):
"""Load Penn TreeBank (PTB) dataset.
It is used in many LANGUAGE MODELING papers,
including "Empirical Evaluation and Combination of Advanced Language
Modeling Techniques", "Recurrent Neural Network Regularization".
It consists of 929k training words, 73k validation words, and 82k test
words. It has 10k words in its vocabulary.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/ptb/``.
Returns
--------
train_data, valid_data, test_data : list of int
The training, validating and testing data in integer format.
vocab_size : int
The vocabulary size.
Examples
--------
>>> train_data, valid_data, test_data, vocab_size = tl.files.load_ptb_dataset()
References
---------------
- ``tensorflow.models.rnn.ptb import reader``
- `Manual download <http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz>`__
Notes
------
- If you want to get the raw data, see the source code.
"""
path = os.path.join(path, 'ptb')
logging.info("Load or Download Penn TreeBank (PTB) dataset > {}".format(path))
# Maybe dowload and uncompress tar, or load exsisting files
filename = 'simple-examples.tgz'
url = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/'
maybe_download_and_extract(filename, path, url, extract=True)
data_path = os.path.join(path, 'simple-examples', 'data')
train_path = os.path.join(data_path, "ptb.train.txt")
valid_path = os.path.join(data_path, "ptb.valid.txt")
test_path = os.path.join(data_path, "ptb.test.txt")
word_to_id = nlp.build_vocab(nlp.read_words(train_path))
train_data = nlp.words_to_word_ids(nlp.read_words(train_path), word_to_id)
valid_data = nlp.words_to_word_ids(nlp.read_words(valid_path), word_to_id)
test_data = nlp.words_to_word_ids(nlp.read_words(test_path), word_to_id)
vocab_size = len(word_to_id)
# logging.info(nlp.read_words(train_path)) # ... 'according', 'to', 'mr.', '<unk>', '<eos>']
# logging.info(train_data) # ... 214, 5, 23, 1, 2]
# logging.info(word_to_id) # ... 'beyond': 1295, 'anti-nuclear': 9599, 'trouble': 1520, '<eos>': 2 ... }
# logging.info(vocabulary) # 10000
# exit()
return train_data, valid_data, test_data, vocab_size | python | def load_ptb_dataset(path='data'):
"""Load Penn TreeBank (PTB) dataset.
It is used in many LANGUAGE MODELING papers,
including "Empirical Evaluation and Combination of Advanced Language
Modeling Techniques", "Recurrent Neural Network Regularization".
It consists of 929k training words, 73k validation words, and 82k test
words. It has 10k words in its vocabulary.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/ptb/``.
Returns
--------
train_data, valid_data, test_data : list of int
The training, validating and testing data in integer format.
vocab_size : int
The vocabulary size.
Examples
--------
>>> train_data, valid_data, test_data, vocab_size = tl.files.load_ptb_dataset()
References
---------------
- ``tensorflow.models.rnn.ptb import reader``
- `Manual download <http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz>`__
Notes
------
- If you want to get the raw data, see the source code.
"""
path = os.path.join(path, 'ptb')
logging.info("Load or Download Penn TreeBank (PTB) dataset > {}".format(path))
# Maybe dowload and uncompress tar, or load exsisting files
filename = 'simple-examples.tgz'
url = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/'
maybe_download_and_extract(filename, path, url, extract=True)
data_path = os.path.join(path, 'simple-examples', 'data')
train_path = os.path.join(data_path, "ptb.train.txt")
valid_path = os.path.join(data_path, "ptb.valid.txt")
test_path = os.path.join(data_path, "ptb.test.txt")
word_to_id = nlp.build_vocab(nlp.read_words(train_path))
train_data = nlp.words_to_word_ids(nlp.read_words(train_path), word_to_id)
valid_data = nlp.words_to_word_ids(nlp.read_words(valid_path), word_to_id)
test_data = nlp.words_to_word_ids(nlp.read_words(test_path), word_to_id)
vocab_size = len(word_to_id)
# logging.info(nlp.read_words(train_path)) # ... 'according', 'to', 'mr.', '<unk>', '<eos>']
# logging.info(train_data) # ... 214, 5, 23, 1, 2]
# logging.info(word_to_id) # ... 'beyond': 1295, 'anti-nuclear': 9599, 'trouble': 1520, '<eos>': 2 ... }
# logging.info(vocabulary) # 10000
# exit()
return train_data, valid_data, test_data, vocab_size | [
"def",
"load_ptb_dataset",
"(",
"path",
"=",
"'data'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'ptb'",
")",
"logging",
".",
"info",
"(",
"\"Load or Download Penn TreeBank (PTB) dataset > {}\"",
".",
"format",
"(",
"path",
")",
")",
"# Maybe dowload and uncompress tar, or load exsisting files",
"filename",
"=",
"'simple-examples.tgz'",
"url",
"=",
"'http://www.fit.vutbr.cz/~imikolov/rnnlm/'",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
",",
"extract",
"=",
"True",
")",
"data_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'simple-examples'",
",",
"'data'",
")",
"train_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_path",
",",
"\"ptb.train.txt\"",
")",
"valid_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_path",
",",
"\"ptb.valid.txt\"",
")",
"test_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_path",
",",
"\"ptb.test.txt\"",
")",
"word_to_id",
"=",
"nlp",
".",
"build_vocab",
"(",
"nlp",
".",
"read_words",
"(",
"train_path",
")",
")",
"train_data",
"=",
"nlp",
".",
"words_to_word_ids",
"(",
"nlp",
".",
"read_words",
"(",
"train_path",
")",
",",
"word_to_id",
")",
"valid_data",
"=",
"nlp",
".",
"words_to_word_ids",
"(",
"nlp",
".",
"read_words",
"(",
"valid_path",
")",
",",
"word_to_id",
")",
"test_data",
"=",
"nlp",
".",
"words_to_word_ids",
"(",
"nlp",
".",
"read_words",
"(",
"test_path",
")",
",",
"word_to_id",
")",
"vocab_size",
"=",
"len",
"(",
"word_to_id",
")",
"# logging.info(nlp.read_words(train_path)) # ... 'according', 'to', 'mr.', '<unk>', '<eos>']",
"# logging.info(train_data) # ... 214, 5, 23, 1, 2]",
"# logging.info(word_to_id) # ... 'beyond': 1295, 'anti-nuclear': 9599, 'trouble': 1520, '<eos>': 2 ... }",
"# logging.info(vocabulary) # 10000",
"# exit()",
"return",
"train_data",
",",
"valid_data",
",",
"test_data",
",",
"vocab_size"
] | Load Penn TreeBank (PTB) dataset.
It is used in many LANGUAGE MODELING papers,
including "Empirical Evaluation and Combination of Advanced Language
Modeling Techniques", "Recurrent Neural Network Regularization".
It consists of 929k training words, 73k validation words, and 82k test
words. It has 10k words in its vocabulary.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/ptb/``.
Returns
--------
train_data, valid_data, test_data : list of int
The training, validating and testing data in integer format.
vocab_size : int
The vocabulary size.
Examples
--------
>>> train_data, valid_data, test_data, vocab_size = tl.files.load_ptb_dataset()
References
---------------
- ``tensorflow.models.rnn.ptb import reader``
- `Manual download <http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz>`__
Notes
------
- If you want to get the raw data, see the source code. | [
"Load",
"Penn",
"TreeBank",
"(",
"PTB",
")",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L413-L473 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_matt_mahoney_text8_dataset | def load_matt_mahoney_text8_dataset(path='data'):
"""Load Matt Mahoney's dataset.
Download a text file from Matt Mahoney's website
if not present, and make sure it's the right size.
Extract the first file enclosed in a zip file as a list of words.
This dataset can be used for Word Embedding.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/mm_test8/``.
Returns
--------
list of str
The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]
Examples
--------
>>> words = tl.files.load_matt_mahoney_text8_dataset()
>>> print('Data size', len(words))
"""
path = os.path.join(path, 'mm_test8')
logging.info("Load or Download matt_mahoney_text8 Dataset> {}".format(path))
filename = 'text8.zip'
url = 'http://mattmahoney.net/dc/'
maybe_download_and_extract(filename, path, url, expected_bytes=31344016)
with zipfile.ZipFile(os.path.join(path, filename)) as f:
word_list = f.read(f.namelist()[0]).split()
for idx, _ in enumerate(word_list):
word_list[idx] = word_list[idx].decode()
return word_list | python | def load_matt_mahoney_text8_dataset(path='data'):
"""Load Matt Mahoney's dataset.
Download a text file from Matt Mahoney's website
if not present, and make sure it's the right size.
Extract the first file enclosed in a zip file as a list of words.
This dataset can be used for Word Embedding.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/mm_test8/``.
Returns
--------
list of str
The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]
Examples
--------
>>> words = tl.files.load_matt_mahoney_text8_dataset()
>>> print('Data size', len(words))
"""
path = os.path.join(path, 'mm_test8')
logging.info("Load or Download matt_mahoney_text8 Dataset> {}".format(path))
filename = 'text8.zip'
url = 'http://mattmahoney.net/dc/'
maybe_download_and_extract(filename, path, url, expected_bytes=31344016)
with zipfile.ZipFile(os.path.join(path, filename)) as f:
word_list = f.read(f.namelist()[0]).split()
for idx, _ in enumerate(word_list):
word_list[idx] = word_list[idx].decode()
return word_list | [
"def",
"load_matt_mahoney_text8_dataset",
"(",
"path",
"=",
"'data'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'mm_test8'",
")",
"logging",
".",
"info",
"(",
"\"Load or Download matt_mahoney_text8 Dataset> {}\"",
".",
"format",
"(",
"path",
")",
")",
"filename",
"=",
"'text8.zip'",
"url",
"=",
"'http://mattmahoney.net/dc/'",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
",",
"expected_bytes",
"=",
"31344016",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
"as",
"f",
":",
"word_list",
"=",
"f",
".",
"read",
"(",
"f",
".",
"namelist",
"(",
")",
"[",
"0",
"]",
")",
".",
"split",
"(",
")",
"for",
"idx",
",",
"_",
"in",
"enumerate",
"(",
"word_list",
")",
":",
"word_list",
"[",
"idx",
"]",
"=",
"word_list",
"[",
"idx",
"]",
".",
"decode",
"(",
")",
"return",
"word_list"
] | Load Matt Mahoney's dataset.
Download a text file from Matt Mahoney's website
if not present, and make sure it's the right size.
Extract the first file enclosed in a zip file as a list of words.
This dataset can be used for Word Embedding.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/mm_test8/``.
Returns
--------
list of str
The raw text data e.g. [.... 'their', 'families', 'who', 'were', 'expelled', 'from', 'jerusalem', ...]
Examples
--------
>>> words = tl.files.load_matt_mahoney_text8_dataset()
>>> print('Data size', len(words)) | [
"Load",
"Matt",
"Mahoney",
"s",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L476-L511 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_imdb_dataset | def load_imdb_dataset(
path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2,
index_from=3
):
"""Load IMDB dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/imdb/``.
nb_words : int
Number of words to get.
skip_top : int
Top most frequent words to ignore (they will appear as oov_char value in the sequence data).
maxlen : int
Maximum sequence length. Any longer sequence will be truncated.
seed : int
Seed for reproducible data shuffling.
start_char : int
The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.
oov_char : int
Words that were cut out because of the num_words or skip_top limit will be replaced with this character.
index_from : int
Index actual words with this index and higher.
Examples
--------
>>> X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(
... nb_words=20000, test_split=0.2)
>>> print('X_train.shape', X_train.shape)
(20000,) [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]
>>> print('y_train.shape', y_train.shape)
(20000,) [1 0 0 ..., 1 0 1]
References
-----------
- `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__
"""
path = os.path.join(path, 'imdb')
filename = "imdb.pkl"
url = 'https://s3.amazonaws.com/text-datasets/'
maybe_download_and_extract(filename, path, url)
if filename.endswith(".gz"):
f = gzip.open(os.path.join(path, filename), 'rb')
else:
f = open(os.path.join(path, filename), 'rb')
X, labels = cPickle.load(f)
f.close()
np.random.seed(seed)
np.random.shuffle(X)
np.random.seed(seed)
np.random.shuffle(labels)
if start_char is not None:
X = [[start_char] + [w + index_from for w in x] for x in X]
elif index_from:
X = [[w + index_from for w in x] for x in X]
if maxlen:
new_X = []
new_labels = []
for x, y in zip(X, labels):
if len(x) < maxlen:
new_X.append(x)
new_labels.append(y)
X = new_X
labels = new_labels
if not X:
raise Exception(
'After filtering for sequences shorter than maxlen=' + str(maxlen) + ', no sequence was kept. '
'Increase maxlen.'
)
if not nb_words:
nb_words = max([max(x) for x in X])
# by convention, use 2 as OOV word
# reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)
if oov_char is not None:
X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]
else:
nX = []
for x in X:
nx = []
for w in x:
if (w >= nb_words or w < skip_top):
nx.append(w)
nX.append(nx)
X = nX
X_train = np.array(X[:int(len(X) * (1 - test_split))])
y_train = np.array(labels[:int(len(X) * (1 - test_split))])
X_test = np.array(X[int(len(X) * (1 - test_split)):])
y_test = np.array(labels[int(len(X) * (1 - test_split)):])
return X_train, y_train, X_test, y_test | python | def load_imdb_dataset(
path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2,
index_from=3
):
"""Load IMDB dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/imdb/``.
nb_words : int
Number of words to get.
skip_top : int
Top most frequent words to ignore (they will appear as oov_char value in the sequence data).
maxlen : int
Maximum sequence length. Any longer sequence will be truncated.
seed : int
Seed for reproducible data shuffling.
start_char : int
The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.
oov_char : int
Words that were cut out because of the num_words or skip_top limit will be replaced with this character.
index_from : int
Index actual words with this index and higher.
Examples
--------
>>> X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(
... nb_words=20000, test_split=0.2)
>>> print('X_train.shape', X_train.shape)
(20000,) [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]
>>> print('y_train.shape', y_train.shape)
(20000,) [1 0 0 ..., 1 0 1]
References
-----------
- `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__
"""
path = os.path.join(path, 'imdb')
filename = "imdb.pkl"
url = 'https://s3.amazonaws.com/text-datasets/'
maybe_download_and_extract(filename, path, url)
if filename.endswith(".gz"):
f = gzip.open(os.path.join(path, filename), 'rb')
else:
f = open(os.path.join(path, filename), 'rb')
X, labels = cPickle.load(f)
f.close()
np.random.seed(seed)
np.random.shuffle(X)
np.random.seed(seed)
np.random.shuffle(labels)
if start_char is not None:
X = [[start_char] + [w + index_from for w in x] for x in X]
elif index_from:
X = [[w + index_from for w in x] for x in X]
if maxlen:
new_X = []
new_labels = []
for x, y in zip(X, labels):
if len(x) < maxlen:
new_X.append(x)
new_labels.append(y)
X = new_X
labels = new_labels
if not X:
raise Exception(
'After filtering for sequences shorter than maxlen=' + str(maxlen) + ', no sequence was kept. '
'Increase maxlen.'
)
if not nb_words:
nb_words = max([max(x) for x in X])
# by convention, use 2 as OOV word
# reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)
if oov_char is not None:
X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]
else:
nX = []
for x in X:
nx = []
for w in x:
if (w >= nb_words or w < skip_top):
nx.append(w)
nX.append(nx)
X = nX
X_train = np.array(X[:int(len(X) * (1 - test_split))])
y_train = np.array(labels[:int(len(X) * (1 - test_split))])
X_test = np.array(X[int(len(X) * (1 - test_split)):])
y_test = np.array(labels[int(len(X) * (1 - test_split)):])
return X_train, y_train, X_test, y_test | [
"def",
"load_imdb_dataset",
"(",
"path",
"=",
"'data'",
",",
"nb_words",
"=",
"None",
",",
"skip_top",
"=",
"0",
",",
"maxlen",
"=",
"None",
",",
"test_split",
"=",
"0.2",
",",
"seed",
"=",
"113",
",",
"start_char",
"=",
"1",
",",
"oov_char",
"=",
"2",
",",
"index_from",
"=",
"3",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'imdb'",
")",
"filename",
"=",
"\"imdb.pkl\"",
"url",
"=",
"'https://s3.amazonaws.com/text-datasets/'",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
")",
"if",
"filename",
".",
"endswith",
"(",
"\".gz\"",
")",
":",
"f",
"=",
"gzip",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
",",
"'rb'",
")",
"else",
":",
"f",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
",",
"'rb'",
")",
"X",
",",
"labels",
"=",
"cPickle",
".",
"load",
"(",
"f",
")",
"f",
".",
"close",
"(",
")",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"np",
".",
"random",
".",
"shuffle",
"(",
"X",
")",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"np",
".",
"random",
".",
"shuffle",
"(",
"labels",
")",
"if",
"start_char",
"is",
"not",
"None",
":",
"X",
"=",
"[",
"[",
"start_char",
"]",
"+",
"[",
"w",
"+",
"index_from",
"for",
"w",
"in",
"x",
"]",
"for",
"x",
"in",
"X",
"]",
"elif",
"index_from",
":",
"X",
"=",
"[",
"[",
"w",
"+",
"index_from",
"for",
"w",
"in",
"x",
"]",
"for",
"x",
"in",
"X",
"]",
"if",
"maxlen",
":",
"new_X",
"=",
"[",
"]",
"new_labels",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"X",
",",
"labels",
")",
":",
"if",
"len",
"(",
"x",
")",
"<",
"maxlen",
":",
"new_X",
".",
"append",
"(",
"x",
")",
"new_labels",
".",
"append",
"(",
"y",
")",
"X",
"=",
"new_X",
"labels",
"=",
"new_labels",
"if",
"not",
"X",
":",
"raise",
"Exception",
"(",
"'After filtering for sequences shorter than maxlen='",
"+",
"str",
"(",
"maxlen",
")",
"+",
"', no sequence was kept. '",
"'Increase maxlen.'",
")",
"if",
"not",
"nb_words",
":",
"nb_words",
"=",
"max",
"(",
"[",
"max",
"(",
"x",
")",
"for",
"x",
"in",
"X",
"]",
")",
"# by convention, use 2 as OOV word",
"# reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)",
"if",
"oov_char",
"is",
"not",
"None",
":",
"X",
"=",
"[",
"[",
"oov_char",
"if",
"(",
"w",
">=",
"nb_words",
"or",
"w",
"<",
"skip_top",
")",
"else",
"w",
"for",
"w",
"in",
"x",
"]",
"for",
"x",
"in",
"X",
"]",
"else",
":",
"nX",
"=",
"[",
"]",
"for",
"x",
"in",
"X",
":",
"nx",
"=",
"[",
"]",
"for",
"w",
"in",
"x",
":",
"if",
"(",
"w",
">=",
"nb_words",
"or",
"w",
"<",
"skip_top",
")",
":",
"nx",
".",
"append",
"(",
"w",
")",
"nX",
".",
"append",
"(",
"nx",
")",
"X",
"=",
"nX",
"X_train",
"=",
"np",
".",
"array",
"(",
"X",
"[",
":",
"int",
"(",
"len",
"(",
"X",
")",
"*",
"(",
"1",
"-",
"test_split",
")",
")",
"]",
")",
"y_train",
"=",
"np",
".",
"array",
"(",
"labels",
"[",
":",
"int",
"(",
"len",
"(",
"X",
")",
"*",
"(",
"1",
"-",
"test_split",
")",
")",
"]",
")",
"X_test",
"=",
"np",
".",
"array",
"(",
"X",
"[",
"int",
"(",
"len",
"(",
"X",
")",
"*",
"(",
"1",
"-",
"test_split",
")",
")",
":",
"]",
")",
"y_test",
"=",
"np",
".",
"array",
"(",
"labels",
"[",
"int",
"(",
"len",
"(",
"X",
")",
"*",
"(",
"1",
"-",
"test_split",
")",
")",
":",
"]",
")",
"return",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test"
] | Load IMDB dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/imdb/``.
nb_words : int
Number of words to get.
skip_top : int
Top most frequent words to ignore (they will appear as oov_char value in the sequence data).
maxlen : int
Maximum sequence length. Any longer sequence will be truncated.
seed : int
Seed for reproducible data shuffling.
start_char : int
The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.
oov_char : int
Words that were cut out because of the num_words or skip_top limit will be replaced with this character.
index_from : int
Index actual words with this index and higher.
Examples
--------
>>> X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(
... nb_words=20000, test_split=0.2)
>>> print('X_train.shape', X_train.shape)
(20000,) [[1, 62, 74, ... 1033, 507, 27],[1, 60, 33, ... 13, 1053, 7]..]
>>> print('y_train.shape', y_train.shape)
(20000,) [1 0 0 ..., 1 0 1]
References
-----------
- `Modified from keras. <https://github.com/fchollet/keras/blob/master/keras/datasets/imdb.py>`__ | [
"Load",
"IMDB",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L514-L614 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_nietzsche_dataset | def load_nietzsche_dataset(path='data'):
"""Load Nietzsche dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/nietzsche/``.
Returns
--------
str
The content.
Examples
--------
>>> see tutorial_generate_text.py
>>> words = tl.files.load_nietzsche_dataset()
>>> words = basic_clean_str(words)
>>> words = words.split()
"""
logging.info("Load or Download nietzsche dataset > {}".format(path))
path = os.path.join(path, 'nietzsche')
filename = "nietzsche.txt"
url = 'https://s3.amazonaws.com/text-datasets/'
filepath = maybe_download_and_extract(filename, path, url)
with open(filepath, "r") as f:
words = f.read()
return words | python | def load_nietzsche_dataset(path='data'):
"""Load Nietzsche dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/nietzsche/``.
Returns
--------
str
The content.
Examples
--------
>>> see tutorial_generate_text.py
>>> words = tl.files.load_nietzsche_dataset()
>>> words = basic_clean_str(words)
>>> words = words.split()
"""
logging.info("Load or Download nietzsche dataset > {}".format(path))
path = os.path.join(path, 'nietzsche')
filename = "nietzsche.txt"
url = 'https://s3.amazonaws.com/text-datasets/'
filepath = maybe_download_and_extract(filename, path, url)
with open(filepath, "r") as f:
words = f.read()
return words | [
"def",
"load_nietzsche_dataset",
"(",
"path",
"=",
"'data'",
")",
":",
"logging",
".",
"info",
"(",
"\"Load or Download nietzsche dataset > {}\"",
".",
"format",
"(",
"path",
")",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'nietzsche'",
")",
"filename",
"=",
"\"nietzsche.txt\"",
"url",
"=",
"'https://s3.amazonaws.com/text-datasets/'",
"filepath",
"=",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
")",
"with",
"open",
"(",
"filepath",
",",
"\"r\"",
")",
"as",
"f",
":",
"words",
"=",
"f",
".",
"read",
"(",
")",
"return",
"words"
] | Load Nietzsche dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/nietzsche/``.
Returns
--------
str
The content.
Examples
--------
>>> see tutorial_generate_text.py
>>> words = tl.files.load_nietzsche_dataset()
>>> words = basic_clean_str(words)
>>> words = words.split() | [
"Load",
"Nietzsche",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L617-L647 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_wmt_en_fr_dataset | def load_wmt_en_fr_dataset(path='data'):
"""Load WMT'15 English-to-French translation dataset.
It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.
Returns the directories of training data and test data.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.
References
----------
- Code modified from /tensorflow/models/rnn/translation/data_utils.py
Notes
-----
Usually, it will take a long time to download this dataset.
"""
path = os.path.join(path, 'wmt_en_fr')
# URLs for WMT data.
_WMT_ENFR_TRAIN_URL = "http://www.statmt.org/wmt10/"
_WMT_ENFR_DEV_URL = "http://www.statmt.org/wmt15/"
def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path."""
logging.info("Unpacking %s to %s" % (gz_path, new_path))
with gzip.open(gz_path, "rb") as gz_file:
with open(new_path, "wb") as new_file:
for line in gz_file:
new_file.write(line)
def get_wmt_enfr_train_set(path):
"""Download the WMT en-fr training corpus to directory unless it's there."""
filename = "training-giga-fren.tar"
maybe_download_and_extract(filename, path, _WMT_ENFR_TRAIN_URL, extract=True)
train_path = os.path.join(path, "giga-fren.release2.fixed")
gunzip_file(train_path + ".fr.gz", train_path + ".fr")
gunzip_file(train_path + ".en.gz", train_path + ".en")
return train_path
def get_wmt_enfr_dev_set(path):
"""Download the WMT en-fr training corpus to directory unless it's there."""
filename = "dev-v2.tgz"
dev_file = maybe_download_and_extract(filename, path, _WMT_ENFR_DEV_URL, extract=False)
dev_name = "newstest2013"
dev_path = os.path.join(path, "newstest2013")
if not (gfile.Exists(dev_path + ".fr") and gfile.Exists(dev_path + ".en")):
logging.info("Extracting tgz file %s" % dev_file)
with tarfile.open(dev_file, "r:gz") as dev_tar:
fr_dev_file = dev_tar.getmember("dev/" + dev_name + ".fr")
en_dev_file = dev_tar.getmember("dev/" + dev_name + ".en")
fr_dev_file.name = dev_name + ".fr" # Extract without "dev/" prefix.
en_dev_file.name = dev_name + ".en"
dev_tar.extract(fr_dev_file, path)
dev_tar.extract(en_dev_file, path)
return dev_path
logging.info("Load or Download WMT English-to-French translation > {}".format(path))
train_path = get_wmt_enfr_train_set(path)
dev_path = get_wmt_enfr_dev_set(path)
return train_path, dev_path | python | def load_wmt_en_fr_dataset(path='data'):
"""Load WMT'15 English-to-French translation dataset.
It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.
Returns the directories of training data and test data.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.
References
----------
- Code modified from /tensorflow/models/rnn/translation/data_utils.py
Notes
-----
Usually, it will take a long time to download this dataset.
"""
path = os.path.join(path, 'wmt_en_fr')
# URLs for WMT data.
_WMT_ENFR_TRAIN_URL = "http://www.statmt.org/wmt10/"
_WMT_ENFR_DEV_URL = "http://www.statmt.org/wmt15/"
def gunzip_file(gz_path, new_path):
"""Unzips from gz_path into new_path."""
logging.info("Unpacking %s to %s" % (gz_path, new_path))
with gzip.open(gz_path, "rb") as gz_file:
with open(new_path, "wb") as new_file:
for line in gz_file:
new_file.write(line)
def get_wmt_enfr_train_set(path):
"""Download the WMT en-fr training corpus to directory unless it's there."""
filename = "training-giga-fren.tar"
maybe_download_and_extract(filename, path, _WMT_ENFR_TRAIN_URL, extract=True)
train_path = os.path.join(path, "giga-fren.release2.fixed")
gunzip_file(train_path + ".fr.gz", train_path + ".fr")
gunzip_file(train_path + ".en.gz", train_path + ".en")
return train_path
def get_wmt_enfr_dev_set(path):
"""Download the WMT en-fr training corpus to directory unless it's there."""
filename = "dev-v2.tgz"
dev_file = maybe_download_and_extract(filename, path, _WMT_ENFR_DEV_URL, extract=False)
dev_name = "newstest2013"
dev_path = os.path.join(path, "newstest2013")
if not (gfile.Exists(dev_path + ".fr") and gfile.Exists(dev_path + ".en")):
logging.info("Extracting tgz file %s" % dev_file)
with tarfile.open(dev_file, "r:gz") as dev_tar:
fr_dev_file = dev_tar.getmember("dev/" + dev_name + ".fr")
en_dev_file = dev_tar.getmember("dev/" + dev_name + ".en")
fr_dev_file.name = dev_name + ".fr" # Extract without "dev/" prefix.
en_dev_file.name = dev_name + ".en"
dev_tar.extract(fr_dev_file, path)
dev_tar.extract(en_dev_file, path)
return dev_path
logging.info("Load or Download WMT English-to-French translation > {}".format(path))
train_path = get_wmt_enfr_train_set(path)
dev_path = get_wmt_enfr_dev_set(path)
return train_path, dev_path | [
"def",
"load_wmt_en_fr_dataset",
"(",
"path",
"=",
"'data'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'wmt_en_fr'",
")",
"# URLs for WMT data.",
"_WMT_ENFR_TRAIN_URL",
"=",
"\"http://www.statmt.org/wmt10/\"",
"_WMT_ENFR_DEV_URL",
"=",
"\"http://www.statmt.org/wmt15/\"",
"def",
"gunzip_file",
"(",
"gz_path",
",",
"new_path",
")",
":",
"\"\"\"Unzips from gz_path into new_path.\"\"\"",
"logging",
".",
"info",
"(",
"\"Unpacking %s to %s\"",
"%",
"(",
"gz_path",
",",
"new_path",
")",
")",
"with",
"gzip",
".",
"open",
"(",
"gz_path",
",",
"\"rb\"",
")",
"as",
"gz_file",
":",
"with",
"open",
"(",
"new_path",
",",
"\"wb\"",
")",
"as",
"new_file",
":",
"for",
"line",
"in",
"gz_file",
":",
"new_file",
".",
"write",
"(",
"line",
")",
"def",
"get_wmt_enfr_train_set",
"(",
"path",
")",
":",
"\"\"\"Download the WMT en-fr training corpus to directory unless it's there.\"\"\"",
"filename",
"=",
"\"training-giga-fren.tar\"",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"_WMT_ENFR_TRAIN_URL",
",",
"extract",
"=",
"True",
")",
"train_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"giga-fren.release2.fixed\"",
")",
"gunzip_file",
"(",
"train_path",
"+",
"\".fr.gz\"",
",",
"train_path",
"+",
"\".fr\"",
")",
"gunzip_file",
"(",
"train_path",
"+",
"\".en.gz\"",
",",
"train_path",
"+",
"\".en\"",
")",
"return",
"train_path",
"def",
"get_wmt_enfr_dev_set",
"(",
"path",
")",
":",
"\"\"\"Download the WMT en-fr training corpus to directory unless it's there.\"\"\"",
"filename",
"=",
"\"dev-v2.tgz\"",
"dev_file",
"=",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"_WMT_ENFR_DEV_URL",
",",
"extract",
"=",
"False",
")",
"dev_name",
"=",
"\"newstest2013\"",
"dev_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"newstest2013\"",
")",
"if",
"not",
"(",
"gfile",
".",
"Exists",
"(",
"dev_path",
"+",
"\".fr\"",
")",
"and",
"gfile",
".",
"Exists",
"(",
"dev_path",
"+",
"\".en\"",
")",
")",
":",
"logging",
".",
"info",
"(",
"\"Extracting tgz file %s\"",
"%",
"dev_file",
")",
"with",
"tarfile",
".",
"open",
"(",
"dev_file",
",",
"\"r:gz\"",
")",
"as",
"dev_tar",
":",
"fr_dev_file",
"=",
"dev_tar",
".",
"getmember",
"(",
"\"dev/\"",
"+",
"dev_name",
"+",
"\".fr\"",
")",
"en_dev_file",
"=",
"dev_tar",
".",
"getmember",
"(",
"\"dev/\"",
"+",
"dev_name",
"+",
"\".en\"",
")",
"fr_dev_file",
".",
"name",
"=",
"dev_name",
"+",
"\".fr\"",
"# Extract without \"dev/\" prefix.",
"en_dev_file",
".",
"name",
"=",
"dev_name",
"+",
"\".en\"",
"dev_tar",
".",
"extract",
"(",
"fr_dev_file",
",",
"path",
")",
"dev_tar",
".",
"extract",
"(",
"en_dev_file",
",",
"path",
")",
"return",
"dev_path",
"logging",
".",
"info",
"(",
"\"Load or Download WMT English-to-French translation > {}\"",
".",
"format",
"(",
"path",
")",
")",
"train_path",
"=",
"get_wmt_enfr_train_set",
"(",
"path",
")",
"dev_path",
"=",
"get_wmt_enfr_dev_set",
"(",
"path",
")",
"return",
"train_path",
",",
"dev_path"
] | Load WMT'15 English-to-French translation dataset.
It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.
Returns the directories of training data and test data.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/wmt_en_fr/``.
References
----------
- Code modified from /tensorflow/models/rnn/translation/data_utils.py
Notes
-----
Usually, it will take a long time to download this dataset. | [
"Load",
"WMT",
"15",
"English",
"-",
"to",
"-",
"French",
"translation",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L650-L714 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_flickr25k_dataset | def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False):
"""Load Flickr25K dataset.
Returns a list of images by a given tag from Flick25k dataset,
it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you use it.
Parameters
------------
tag : str or None
What images to return.
- If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
- If you want to get all images, set to ``None``.
path : str
The path that the data is downloaded to, defaults is ``data/flickr25k/``.
n_threads : int
The number of thread to read image.
printable : boolean
Whether to print infomation when reading images, default is ``False``.
Examples
-----------
Get images with tag of sky
>>> images = tl.files.load_flickr25k_dataset(tag='sky')
Get all images
>>> images = tl.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True)
"""
path = os.path.join(path, 'flickr25k')
filename = 'mirflickr25k.zip'
url = 'http://press.liacs.nl/mirflickr/mirflickr25k/'
# download dataset
if folder_exists(os.path.join(path, "mirflickr")) is False:
logging.info("[*] Flickr25k is nonexistent in {}".format(path))
maybe_download_and_extract(filename, path, url, extract=True)
del_file(os.path.join(path, filename))
# return images by the given tag.
# 1. image path list
folder_imgs = os.path.join(path, "mirflickr")
path_imgs = load_file_list(path=folder_imgs, regx='\\.jpg', printable=False)
path_imgs.sort(key=natural_keys)
# 2. tag path list
folder_tags = os.path.join(path, "mirflickr", "meta", "tags")
path_tags = load_file_list(path=folder_tags, regx='\\.txt', printable=False)
path_tags.sort(key=natural_keys)
# 3. select images
if tag is None:
logging.info("[Flickr25k] reading all images")
else:
logging.info("[Flickr25k] reading images with tag: {}".format(tag))
images_list = []
for idx, _v in enumerate(path_tags):
tags = read_file(os.path.join(folder_tags, path_tags[idx])).split('\n')
# logging.info(idx+1, tags)
if tag is None or tag in tags:
images_list.append(path_imgs[idx])
images = visualize.read_images(images_list, folder_imgs, n_threads=n_threads, printable=printable)
return images | python | def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False):
"""Load Flickr25K dataset.
Returns a list of images by a given tag from Flick25k dataset,
it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you use it.
Parameters
------------
tag : str or None
What images to return.
- If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
- If you want to get all images, set to ``None``.
path : str
The path that the data is downloaded to, defaults is ``data/flickr25k/``.
n_threads : int
The number of thread to read image.
printable : boolean
Whether to print infomation when reading images, default is ``False``.
Examples
-----------
Get images with tag of sky
>>> images = tl.files.load_flickr25k_dataset(tag='sky')
Get all images
>>> images = tl.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True)
"""
path = os.path.join(path, 'flickr25k')
filename = 'mirflickr25k.zip'
url = 'http://press.liacs.nl/mirflickr/mirflickr25k/'
# download dataset
if folder_exists(os.path.join(path, "mirflickr")) is False:
logging.info("[*] Flickr25k is nonexistent in {}".format(path))
maybe_download_and_extract(filename, path, url, extract=True)
del_file(os.path.join(path, filename))
# return images by the given tag.
# 1. image path list
folder_imgs = os.path.join(path, "mirflickr")
path_imgs = load_file_list(path=folder_imgs, regx='\\.jpg', printable=False)
path_imgs.sort(key=natural_keys)
# 2. tag path list
folder_tags = os.path.join(path, "mirflickr", "meta", "tags")
path_tags = load_file_list(path=folder_tags, regx='\\.txt', printable=False)
path_tags.sort(key=natural_keys)
# 3. select images
if tag is None:
logging.info("[Flickr25k] reading all images")
else:
logging.info("[Flickr25k] reading images with tag: {}".format(tag))
images_list = []
for idx, _v in enumerate(path_tags):
tags = read_file(os.path.join(folder_tags, path_tags[idx])).split('\n')
# logging.info(idx+1, tags)
if tag is None or tag in tags:
images_list.append(path_imgs[idx])
images = visualize.read_images(images_list, folder_imgs, n_threads=n_threads, printable=printable)
return images | [
"def",
"load_flickr25k_dataset",
"(",
"tag",
"=",
"'sky'",
",",
"path",
"=",
"\"data\"",
",",
"n_threads",
"=",
"50",
",",
"printable",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'flickr25k'",
")",
"filename",
"=",
"'mirflickr25k.zip'",
"url",
"=",
"'http://press.liacs.nl/mirflickr/mirflickr25k/'",
"# download dataset",
"if",
"folder_exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"mirflickr\"",
")",
")",
"is",
"False",
":",
"logging",
".",
"info",
"(",
"\"[*] Flickr25k is nonexistent in {}\"",
".",
"format",
"(",
"path",
")",
")",
"maybe_download_and_extract",
"(",
"filename",
",",
"path",
",",
"url",
",",
"extract",
"=",
"True",
")",
"del_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
"# return images by the given tag.",
"# 1. image path list",
"folder_imgs",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"mirflickr\"",
")",
"path_imgs",
"=",
"load_file_list",
"(",
"path",
"=",
"folder_imgs",
",",
"regx",
"=",
"'\\\\.jpg'",
",",
"printable",
"=",
"False",
")",
"path_imgs",
".",
"sort",
"(",
"key",
"=",
"natural_keys",
")",
"# 2. tag path list",
"folder_tags",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"mirflickr\"",
",",
"\"meta\"",
",",
"\"tags\"",
")",
"path_tags",
"=",
"load_file_list",
"(",
"path",
"=",
"folder_tags",
",",
"regx",
"=",
"'\\\\.txt'",
",",
"printable",
"=",
"False",
")",
"path_tags",
".",
"sort",
"(",
"key",
"=",
"natural_keys",
")",
"# 3. select images",
"if",
"tag",
"is",
"None",
":",
"logging",
".",
"info",
"(",
"\"[Flickr25k] reading all images\"",
")",
"else",
":",
"logging",
".",
"info",
"(",
"\"[Flickr25k] reading images with tag: {}\"",
".",
"format",
"(",
"tag",
")",
")",
"images_list",
"=",
"[",
"]",
"for",
"idx",
",",
"_v",
"in",
"enumerate",
"(",
"path_tags",
")",
":",
"tags",
"=",
"read_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"folder_tags",
",",
"path_tags",
"[",
"idx",
"]",
")",
")",
".",
"split",
"(",
"'\\n'",
")",
"# logging.info(idx+1, tags)",
"if",
"tag",
"is",
"None",
"or",
"tag",
"in",
"tags",
":",
"images_list",
".",
"append",
"(",
"path_imgs",
"[",
"idx",
"]",
")",
"images",
"=",
"visualize",
".",
"read_images",
"(",
"images_list",
",",
"folder_imgs",
",",
"n_threads",
"=",
"n_threads",
",",
"printable",
"=",
"printable",
")",
"return",
"images"
] | Load Flickr25K dataset.
Returns a list of images by a given tag from Flick25k dataset,
it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you use it.
Parameters
------------
tag : str or None
What images to return.
- If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
- If you want to get all images, set to ``None``.
path : str
The path that the data is downloaded to, defaults is ``data/flickr25k/``.
n_threads : int
The number of thread to read image.
printable : boolean
Whether to print infomation when reading images, default is ``False``.
Examples
-----------
Get images with tag of sky
>>> images = tl.files.load_flickr25k_dataset(tag='sky')
Get all images
>>> images = tl.files.load_flickr25k_dataset(tag=None, n_threads=100, printable=True) | [
"Load",
"Flickr25K",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L717-L784 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_flickr1M_dataset | def load_flickr1M_dataset(tag='sky', size=10, path="data", n_threads=50, printable=False):
"""Load Flick1M dataset.
Returns a list of images by a given tag from Flickr1M dataset,
it will download Flickr1M from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you use it.
Parameters
------------
tag : str or None
What images to return.
- If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
- If you want to get all images, set to ``None``.
size : int
integer between 1 to 10. 1 means 100k images ... 5 means 500k images, 10 means all 1 million images. Default is 10.
path : str
The path that the data is downloaded to, defaults is ``data/flickr25k/``.
n_threads : int
The number of thread to read image.
printable : boolean
Whether to print infomation when reading images, default is ``False``.
Examples
----------
Use 200k images
>>> images = tl.files.load_flickr1M_dataset(tag='zebra', size=2)
Use 1 Million images
>>> images = tl.files.load_flickr1M_dataset(tag='zebra')
"""
path = os.path.join(path, 'flickr1M')
logging.info("[Flickr1M] using {}% of images = {}".format(size * 10, size * 100000))
images_zip = [
'images0.zip', 'images1.zip', 'images2.zip', 'images3.zip', 'images4.zip', 'images5.zip', 'images6.zip',
'images7.zip', 'images8.zip', 'images9.zip'
]
tag_zip = 'tags.zip'
url = 'http://press.liacs.nl/mirflickr/mirflickr1m/'
# download dataset
for image_zip in images_zip[0:size]:
image_folder = image_zip.split(".")[0]
# logging.info(path+"/"+image_folder)
if folder_exists(os.path.join(path, image_folder)) is False:
# logging.info(image_zip)
logging.info("[Flickr1M] {} is missing in {}".format(image_folder, path))
maybe_download_and_extract(image_zip, path, url, extract=True)
del_file(os.path.join(path, image_zip))
# os.system("mv {} {}".format(os.path.join(path, 'images'), os.path.join(path, image_folder)))
shutil.move(os.path.join(path, 'images'), os.path.join(path, image_folder))
else:
logging.info("[Flickr1M] {} exists in {}".format(image_folder, path))
# download tag
if folder_exists(os.path.join(path, "tags")) is False:
logging.info("[Flickr1M] tag files is nonexistent in {}".format(path))
maybe_download_and_extract(tag_zip, path, url, extract=True)
del_file(os.path.join(path, tag_zip))
else:
logging.info("[Flickr1M] tags exists in {}".format(path))
# 1. image path list
images_list = []
images_folder_list = []
for i in range(0, size):
images_folder_list += load_folder_list(path=os.path.join(path, 'images%d' % i))
images_folder_list.sort(key=lambda s: int(s.split('/')[-1])) # folder/images/ddd
for folder in images_folder_list[0:size * 10]:
tmp = load_file_list(path=folder, regx='\\.jpg', printable=False)
tmp.sort(key=lambda s: int(s.split('.')[-2])) # ddd.jpg
images_list.extend([os.path.join(folder, x) for x in tmp])
# 2. tag path list
tag_list = []
tag_folder_list = load_folder_list(os.path.join(path, "tags"))
# tag_folder_list.sort(key=lambda s: int(s.split("/")[-1])) # folder/images/ddd
tag_folder_list.sort(key=lambda s: int(os.path.basename(s)))
for folder in tag_folder_list[0:size * 10]:
tmp = load_file_list(path=folder, regx='\\.txt', printable=False)
tmp.sort(key=lambda s: int(s.split('.')[-2])) # ddd.txt
tmp = [os.path.join(folder, s) for s in tmp]
tag_list += tmp
# 3. select images
logging.info("[Flickr1M] searching tag: {}".format(tag))
select_images_list = []
for idx, _val in enumerate(tag_list):
tags = read_file(tag_list[idx]).split('\n')
if tag in tags:
select_images_list.append(images_list[idx])
logging.info("[Flickr1M] reading images with tag: {}".format(tag))
images = visualize.read_images(select_images_list, '', n_threads=n_threads, printable=printable)
return images | python | def load_flickr1M_dataset(tag='sky', size=10, path="data", n_threads=50, printable=False):
"""Load Flick1M dataset.
Returns a list of images by a given tag from Flickr1M dataset,
it will download Flickr1M from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you use it.
Parameters
------------
tag : str or None
What images to return.
- If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
- If you want to get all images, set to ``None``.
size : int
integer between 1 to 10. 1 means 100k images ... 5 means 500k images, 10 means all 1 million images. Default is 10.
path : str
The path that the data is downloaded to, defaults is ``data/flickr25k/``.
n_threads : int
The number of thread to read image.
printable : boolean
Whether to print infomation when reading images, default is ``False``.
Examples
----------
Use 200k images
>>> images = tl.files.load_flickr1M_dataset(tag='zebra', size=2)
Use 1 Million images
>>> images = tl.files.load_flickr1M_dataset(tag='zebra')
"""
path = os.path.join(path, 'flickr1M')
logging.info("[Flickr1M] using {}% of images = {}".format(size * 10, size * 100000))
images_zip = [
'images0.zip', 'images1.zip', 'images2.zip', 'images3.zip', 'images4.zip', 'images5.zip', 'images6.zip',
'images7.zip', 'images8.zip', 'images9.zip'
]
tag_zip = 'tags.zip'
url = 'http://press.liacs.nl/mirflickr/mirflickr1m/'
# download dataset
for image_zip in images_zip[0:size]:
image_folder = image_zip.split(".")[0]
# logging.info(path+"/"+image_folder)
if folder_exists(os.path.join(path, image_folder)) is False:
# logging.info(image_zip)
logging.info("[Flickr1M] {} is missing in {}".format(image_folder, path))
maybe_download_and_extract(image_zip, path, url, extract=True)
del_file(os.path.join(path, image_zip))
# os.system("mv {} {}".format(os.path.join(path, 'images'), os.path.join(path, image_folder)))
shutil.move(os.path.join(path, 'images'), os.path.join(path, image_folder))
else:
logging.info("[Flickr1M] {} exists in {}".format(image_folder, path))
# download tag
if folder_exists(os.path.join(path, "tags")) is False:
logging.info("[Flickr1M] tag files is nonexistent in {}".format(path))
maybe_download_and_extract(tag_zip, path, url, extract=True)
del_file(os.path.join(path, tag_zip))
else:
logging.info("[Flickr1M] tags exists in {}".format(path))
# 1. image path list
images_list = []
images_folder_list = []
for i in range(0, size):
images_folder_list += load_folder_list(path=os.path.join(path, 'images%d' % i))
images_folder_list.sort(key=lambda s: int(s.split('/')[-1])) # folder/images/ddd
for folder in images_folder_list[0:size * 10]:
tmp = load_file_list(path=folder, regx='\\.jpg', printable=False)
tmp.sort(key=lambda s: int(s.split('.')[-2])) # ddd.jpg
images_list.extend([os.path.join(folder, x) for x in tmp])
# 2. tag path list
tag_list = []
tag_folder_list = load_folder_list(os.path.join(path, "tags"))
# tag_folder_list.sort(key=lambda s: int(s.split("/")[-1])) # folder/images/ddd
tag_folder_list.sort(key=lambda s: int(os.path.basename(s)))
for folder in tag_folder_list[0:size * 10]:
tmp = load_file_list(path=folder, regx='\\.txt', printable=False)
tmp.sort(key=lambda s: int(s.split('.')[-2])) # ddd.txt
tmp = [os.path.join(folder, s) for s in tmp]
tag_list += tmp
# 3. select images
logging.info("[Flickr1M] searching tag: {}".format(tag))
select_images_list = []
for idx, _val in enumerate(tag_list):
tags = read_file(tag_list[idx]).split('\n')
if tag in tags:
select_images_list.append(images_list[idx])
logging.info("[Flickr1M] reading images with tag: {}".format(tag))
images = visualize.read_images(select_images_list, '', n_threads=n_threads, printable=printable)
return images | [
"def",
"load_flickr1M_dataset",
"(",
"tag",
"=",
"'sky'",
",",
"size",
"=",
"10",
",",
"path",
"=",
"\"data\"",
",",
"n_threads",
"=",
"50",
",",
"printable",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'flickr1M'",
")",
"logging",
".",
"info",
"(",
"\"[Flickr1M] using {}% of images = {}\"",
".",
"format",
"(",
"size",
"*",
"10",
",",
"size",
"*",
"100000",
")",
")",
"images_zip",
"=",
"[",
"'images0.zip'",
",",
"'images1.zip'",
",",
"'images2.zip'",
",",
"'images3.zip'",
",",
"'images4.zip'",
",",
"'images5.zip'",
",",
"'images6.zip'",
",",
"'images7.zip'",
",",
"'images8.zip'",
",",
"'images9.zip'",
"]",
"tag_zip",
"=",
"'tags.zip'",
"url",
"=",
"'http://press.liacs.nl/mirflickr/mirflickr1m/'",
"# download dataset",
"for",
"image_zip",
"in",
"images_zip",
"[",
"0",
":",
"size",
"]",
":",
"image_folder",
"=",
"image_zip",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"# logging.info(path+\"/\"+image_folder)",
"if",
"folder_exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"image_folder",
")",
")",
"is",
"False",
":",
"# logging.info(image_zip)",
"logging",
".",
"info",
"(",
"\"[Flickr1M] {} is missing in {}\"",
".",
"format",
"(",
"image_folder",
",",
"path",
")",
")",
"maybe_download_and_extract",
"(",
"image_zip",
",",
"path",
",",
"url",
",",
"extract",
"=",
"True",
")",
"del_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"image_zip",
")",
")",
"# os.system(\"mv {} {}\".format(os.path.join(path, 'images'), os.path.join(path, image_folder)))",
"shutil",
".",
"move",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'images'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"image_folder",
")",
")",
"else",
":",
"logging",
".",
"info",
"(",
"\"[Flickr1M] {} exists in {}\"",
".",
"format",
"(",
"image_folder",
",",
"path",
")",
")",
"# download tag",
"if",
"folder_exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"tags\"",
")",
")",
"is",
"False",
":",
"logging",
".",
"info",
"(",
"\"[Flickr1M] tag files is nonexistent in {}\"",
".",
"format",
"(",
"path",
")",
")",
"maybe_download_and_extract",
"(",
"tag_zip",
",",
"path",
",",
"url",
",",
"extract",
"=",
"True",
")",
"del_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"tag_zip",
")",
")",
"else",
":",
"logging",
".",
"info",
"(",
"\"[Flickr1M] tags exists in {}\"",
".",
"format",
"(",
"path",
")",
")",
"# 1. image path list",
"images_list",
"=",
"[",
"]",
"images_folder_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
")",
":",
"images_folder_list",
"+=",
"load_folder_list",
"(",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'images%d'",
"%",
"i",
")",
")",
"images_folder_list",
".",
"sort",
"(",
"key",
"=",
"lambda",
"s",
":",
"int",
"(",
"s",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
")",
")",
"# folder/images/ddd",
"for",
"folder",
"in",
"images_folder_list",
"[",
"0",
":",
"size",
"*",
"10",
"]",
":",
"tmp",
"=",
"load_file_list",
"(",
"path",
"=",
"folder",
",",
"regx",
"=",
"'\\\\.jpg'",
",",
"printable",
"=",
"False",
")",
"tmp",
".",
"sort",
"(",
"key",
"=",
"lambda",
"s",
":",
"int",
"(",
"s",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"2",
"]",
")",
")",
"# ddd.jpg",
"images_list",
".",
"extend",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"x",
")",
"for",
"x",
"in",
"tmp",
"]",
")",
"# 2. tag path list",
"tag_list",
"=",
"[",
"]",
"tag_folder_list",
"=",
"load_folder_list",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"tags\"",
")",
")",
"# tag_folder_list.sort(key=lambda s: int(s.split(\"/\")[-1])) # folder/images/ddd",
"tag_folder_list",
".",
"sort",
"(",
"key",
"=",
"lambda",
"s",
":",
"int",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"s",
")",
")",
")",
"for",
"folder",
"in",
"tag_folder_list",
"[",
"0",
":",
"size",
"*",
"10",
"]",
":",
"tmp",
"=",
"load_file_list",
"(",
"path",
"=",
"folder",
",",
"regx",
"=",
"'\\\\.txt'",
",",
"printable",
"=",
"False",
")",
"tmp",
".",
"sort",
"(",
"key",
"=",
"lambda",
"s",
":",
"int",
"(",
"s",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"2",
"]",
")",
")",
"# ddd.txt",
"tmp",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"s",
")",
"for",
"s",
"in",
"tmp",
"]",
"tag_list",
"+=",
"tmp",
"# 3. select images",
"logging",
".",
"info",
"(",
"\"[Flickr1M] searching tag: {}\"",
".",
"format",
"(",
"tag",
")",
")",
"select_images_list",
"=",
"[",
"]",
"for",
"idx",
",",
"_val",
"in",
"enumerate",
"(",
"tag_list",
")",
":",
"tags",
"=",
"read_file",
"(",
"tag_list",
"[",
"idx",
"]",
")",
".",
"split",
"(",
"'\\n'",
")",
"if",
"tag",
"in",
"tags",
":",
"select_images_list",
".",
"append",
"(",
"images_list",
"[",
"idx",
"]",
")",
"logging",
".",
"info",
"(",
"\"[Flickr1M] reading images with tag: {}\"",
".",
"format",
"(",
"tag",
")",
")",
"images",
"=",
"visualize",
".",
"read_images",
"(",
"select_images_list",
",",
"''",
",",
"n_threads",
"=",
"n_threads",
",",
"printable",
"=",
"printable",
")",
"return",
"images"
] | Load Flick1M dataset.
Returns a list of images by a given tag from Flickr1M dataset,
it will download Flickr1M from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`__
at the first time you use it.
Parameters
------------
tag : str or None
What images to return.
- If you want to get images with tag, use string like 'dog', 'red', see `Flickr Search <https://www.flickr.com/search/>`__.
- If you want to get all images, set to ``None``.
size : int
integer between 1 to 10. 1 means 100k images ... 5 means 500k images, 10 means all 1 million images. Default is 10.
path : str
The path that the data is downloaded to, defaults is ``data/flickr25k/``.
n_threads : int
The number of thread to read image.
printable : boolean
Whether to print infomation when reading images, default is ``False``.
Examples
----------
Use 200k images
>>> images = tl.files.load_flickr1M_dataset(tag='zebra', size=2)
Use 1 Million images
>>> images = tl.files.load_flickr1M_dataset(tag='zebra') | [
"Load",
"Flick1M",
"dataset",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L787-L887 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_cyclegan_dataset | def load_cyclegan_dataset(filename='summer2winter_yosemite', path='data'):
"""Load images from CycleGAN's database, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.
Parameters
------------
filename : str
The dataset you want, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.
path : str
The path that the data is downloaded to, defaults is `data/cyclegan`
Examples
---------
>>> im_train_A, im_train_B, im_test_A, im_test_B = load_cyclegan_dataset(filename='summer2winter_yosemite')
"""
path = os.path.join(path, 'cyclegan')
url = 'https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/'
if folder_exists(os.path.join(path, filename)) is False:
logging.info("[*] {} is nonexistent in {}".format(filename, path))
maybe_download_and_extract(filename + '.zip', path, url, extract=True)
del_file(os.path.join(path, filename + '.zip'))
def load_image_from_folder(path):
path_imgs = load_file_list(path=path, regx='\\.jpg', printable=False)
return visualize.read_images(path_imgs, path=path, n_threads=10, printable=False)
im_train_A = load_image_from_folder(os.path.join(path, filename, "trainA"))
im_train_B = load_image_from_folder(os.path.join(path, filename, "trainB"))
im_test_A = load_image_from_folder(os.path.join(path, filename, "testA"))
im_test_B = load_image_from_folder(os.path.join(path, filename, "testB"))
def if_2d_to_3d(images): # [h, w] --> [h, w, 3]
for i, _v in enumerate(images):
if len(images[i].shape) == 2:
images[i] = images[i][:, :, np.newaxis]
images[i] = np.tile(images[i], (1, 1, 3))
return images
im_train_A = if_2d_to_3d(im_train_A)
im_train_B = if_2d_to_3d(im_train_B)
im_test_A = if_2d_to_3d(im_test_A)
im_test_B = if_2d_to_3d(im_test_B)
return im_train_A, im_train_B, im_test_A, im_test_B | python | def load_cyclegan_dataset(filename='summer2winter_yosemite', path='data'):
"""Load images from CycleGAN's database, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.
Parameters
------------
filename : str
The dataset you want, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.
path : str
The path that the data is downloaded to, defaults is `data/cyclegan`
Examples
---------
>>> im_train_A, im_train_B, im_test_A, im_test_B = load_cyclegan_dataset(filename='summer2winter_yosemite')
"""
path = os.path.join(path, 'cyclegan')
url = 'https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/'
if folder_exists(os.path.join(path, filename)) is False:
logging.info("[*] {} is nonexistent in {}".format(filename, path))
maybe_download_and_extract(filename + '.zip', path, url, extract=True)
del_file(os.path.join(path, filename + '.zip'))
def load_image_from_folder(path):
path_imgs = load_file_list(path=path, regx='\\.jpg', printable=False)
return visualize.read_images(path_imgs, path=path, n_threads=10, printable=False)
im_train_A = load_image_from_folder(os.path.join(path, filename, "trainA"))
im_train_B = load_image_from_folder(os.path.join(path, filename, "trainB"))
im_test_A = load_image_from_folder(os.path.join(path, filename, "testA"))
im_test_B = load_image_from_folder(os.path.join(path, filename, "testB"))
def if_2d_to_3d(images): # [h, w] --> [h, w, 3]
for i, _v in enumerate(images):
if len(images[i].shape) == 2:
images[i] = images[i][:, :, np.newaxis]
images[i] = np.tile(images[i], (1, 1, 3))
return images
im_train_A = if_2d_to_3d(im_train_A)
im_train_B = if_2d_to_3d(im_train_B)
im_test_A = if_2d_to_3d(im_test_A)
im_test_B = if_2d_to_3d(im_test_B)
return im_train_A, im_train_B, im_test_A, im_test_B | [
"def",
"load_cyclegan_dataset",
"(",
"filename",
"=",
"'summer2winter_yosemite'",
",",
"path",
"=",
"'data'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'cyclegan'",
")",
"url",
"=",
"'https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/'",
"if",
"folder_exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
"is",
"False",
":",
"logging",
".",
"info",
"(",
"\"[*] {} is nonexistent in {}\"",
".",
"format",
"(",
"filename",
",",
"path",
")",
")",
"maybe_download_and_extract",
"(",
"filename",
"+",
"'.zip'",
",",
"path",
",",
"url",
",",
"extract",
"=",
"True",
")",
"del_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
"+",
"'.zip'",
")",
")",
"def",
"load_image_from_folder",
"(",
"path",
")",
":",
"path_imgs",
"=",
"load_file_list",
"(",
"path",
"=",
"path",
",",
"regx",
"=",
"'\\\\.jpg'",
",",
"printable",
"=",
"False",
")",
"return",
"visualize",
".",
"read_images",
"(",
"path_imgs",
",",
"path",
"=",
"path",
",",
"n_threads",
"=",
"10",
",",
"printable",
"=",
"False",
")",
"im_train_A",
"=",
"load_image_from_folder",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
",",
"\"trainA\"",
")",
")",
"im_train_B",
"=",
"load_image_from_folder",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
",",
"\"trainB\"",
")",
")",
"im_test_A",
"=",
"load_image_from_folder",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
",",
"\"testA\"",
")",
")",
"im_test_B",
"=",
"load_image_from_folder",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
",",
"\"testB\"",
")",
")",
"def",
"if_2d_to_3d",
"(",
"images",
")",
":",
"# [h, w] --> [h, w, 3]",
"for",
"i",
",",
"_v",
"in",
"enumerate",
"(",
"images",
")",
":",
"if",
"len",
"(",
"images",
"[",
"i",
"]",
".",
"shape",
")",
"==",
"2",
":",
"images",
"[",
"i",
"]",
"=",
"images",
"[",
"i",
"]",
"[",
":",
",",
":",
",",
"np",
".",
"newaxis",
"]",
"images",
"[",
"i",
"]",
"=",
"np",
".",
"tile",
"(",
"images",
"[",
"i",
"]",
",",
"(",
"1",
",",
"1",
",",
"3",
")",
")",
"return",
"images",
"im_train_A",
"=",
"if_2d_to_3d",
"(",
"im_train_A",
")",
"im_train_B",
"=",
"if_2d_to_3d",
"(",
"im_train_B",
")",
"im_test_A",
"=",
"if_2d_to_3d",
"(",
"im_test_A",
")",
"im_test_B",
"=",
"if_2d_to_3d",
"(",
"im_test_B",
")",
"return",
"im_train_A",
",",
"im_train_B",
",",
"im_test_A",
",",
"im_test_B"
] | Load images from CycleGAN's database, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.
Parameters
------------
filename : str
The dataset you want, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__.
path : str
The path that the data is downloaded to, defaults is `data/cyclegan`
Examples
---------
>>> im_train_A, im_train_B, im_test_A, im_test_B = load_cyclegan_dataset(filename='summer2winter_yosemite') | [
"Load",
"images",
"from",
"CycleGAN",
"s",
"database",
"see",
"this",
"link",
"<https",
":",
"//",
"people",
".",
"eecs",
".",
"berkeley",
".",
"edu",
"/",
"~taesung_park",
"/",
"CycleGAN",
"/",
"datasets",
"/",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L890-L934 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | download_file_from_google_drive | def download_file_from_google_drive(ID, destination):
"""Download file from Google Drive.
See ``tl.files.load_celebA_dataset`` for example.
Parameters
--------------
ID : str
The driver ID.
destination : str
The destination for save file.
"""
def save_response_content(response, destination, chunk_size=32 * 1024):
total_size = int(response.headers.get('content-length', 0))
with open(destination, "wb") as f:
for chunk in tqdm(response.iter_content(chunk_size), total=total_size, unit='B', unit_scale=True,
desc=destination):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
def get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
URL = "https://docs.google.com/uc?export=download"
session = requests.Session()
response = session.get(URL, params={'id': ID}, stream=True)
token = get_confirm_token(response)
if token:
params = {'id': ID, 'confirm': token}
response = session.get(URL, params=params, stream=True)
save_response_content(response, destination) | python | def download_file_from_google_drive(ID, destination):
"""Download file from Google Drive.
See ``tl.files.load_celebA_dataset`` for example.
Parameters
--------------
ID : str
The driver ID.
destination : str
The destination for save file.
"""
def save_response_content(response, destination, chunk_size=32 * 1024):
total_size = int(response.headers.get('content-length', 0))
with open(destination, "wb") as f:
for chunk in tqdm(response.iter_content(chunk_size), total=total_size, unit='B', unit_scale=True,
desc=destination):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
def get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
URL = "https://docs.google.com/uc?export=download"
session = requests.Session()
response = session.get(URL, params={'id': ID}, stream=True)
token = get_confirm_token(response)
if token:
params = {'id': ID, 'confirm': token}
response = session.get(URL, params=params, stream=True)
save_response_content(response, destination) | [
"def",
"download_file_from_google_drive",
"(",
"ID",
",",
"destination",
")",
":",
"def",
"save_response_content",
"(",
"response",
",",
"destination",
",",
"chunk_size",
"=",
"32",
"*",
"1024",
")",
":",
"total_size",
"=",
"int",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'content-length'",
",",
"0",
")",
")",
"with",
"open",
"(",
"destination",
",",
"\"wb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"tqdm",
"(",
"response",
".",
"iter_content",
"(",
"chunk_size",
")",
",",
"total",
"=",
"total_size",
",",
"unit",
"=",
"'B'",
",",
"unit_scale",
"=",
"True",
",",
"desc",
"=",
"destination",
")",
":",
"if",
"chunk",
":",
"# filter out keep-alive new chunks",
"f",
".",
"write",
"(",
"chunk",
")",
"def",
"get_confirm_token",
"(",
"response",
")",
":",
"for",
"key",
",",
"value",
"in",
"response",
".",
"cookies",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'download_warning'",
")",
":",
"return",
"value",
"return",
"None",
"URL",
"=",
"\"https://docs.google.com/uc?export=download\"",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"response",
"=",
"session",
".",
"get",
"(",
"URL",
",",
"params",
"=",
"{",
"'id'",
":",
"ID",
"}",
",",
"stream",
"=",
"True",
")",
"token",
"=",
"get_confirm_token",
"(",
"response",
")",
"if",
"token",
":",
"params",
"=",
"{",
"'id'",
":",
"ID",
",",
"'confirm'",
":",
"token",
"}",
"response",
"=",
"session",
".",
"get",
"(",
"URL",
",",
"params",
"=",
"params",
",",
"stream",
"=",
"True",
")",
"save_response_content",
"(",
"response",
",",
"destination",
")"
] | Download file from Google Drive.
See ``tl.files.load_celebA_dataset`` for example.
Parameters
--------------
ID : str
The driver ID.
destination : str
The destination for save file. | [
"Download",
"file",
"from",
"Google",
"Drive",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L937-L974 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_celebA_dataset | def load_celebA_dataset(path='data'):
"""Load CelebA dataset
Return a list of image path.
Parameters
-----------
path : str
The path that the data is downloaded to, defaults is ``data/celebA/``.
"""
data_dir = 'celebA'
filename, drive_id = "img_align_celeba.zip", "0B7EVK8r0v71pZjFTYXZWM3FlRnM"
save_path = os.path.join(path, filename)
image_path = os.path.join(path, data_dir)
if os.path.exists(image_path):
logging.info('[*] {} already exists'.format(save_path))
else:
exists_or_mkdir(path)
download_file_from_google_drive(drive_id, save_path)
zip_dir = ''
with zipfile.ZipFile(save_path) as zf:
zip_dir = zf.namelist()[0]
zf.extractall(path)
os.remove(save_path)
os.rename(os.path.join(path, zip_dir), image_path)
data_files = load_file_list(path=image_path, regx='\\.jpg', printable=False)
for i, _v in enumerate(data_files):
data_files[i] = os.path.join(image_path, data_files[i])
return data_files | python | def load_celebA_dataset(path='data'):
"""Load CelebA dataset
Return a list of image path.
Parameters
-----------
path : str
The path that the data is downloaded to, defaults is ``data/celebA/``.
"""
data_dir = 'celebA'
filename, drive_id = "img_align_celeba.zip", "0B7EVK8r0v71pZjFTYXZWM3FlRnM"
save_path = os.path.join(path, filename)
image_path = os.path.join(path, data_dir)
if os.path.exists(image_path):
logging.info('[*] {} already exists'.format(save_path))
else:
exists_or_mkdir(path)
download_file_from_google_drive(drive_id, save_path)
zip_dir = ''
with zipfile.ZipFile(save_path) as zf:
zip_dir = zf.namelist()[0]
zf.extractall(path)
os.remove(save_path)
os.rename(os.path.join(path, zip_dir), image_path)
data_files = load_file_list(path=image_path, regx='\\.jpg', printable=False)
for i, _v in enumerate(data_files):
data_files[i] = os.path.join(image_path, data_files[i])
return data_files | [
"def",
"load_celebA_dataset",
"(",
"path",
"=",
"'data'",
")",
":",
"data_dir",
"=",
"'celebA'",
"filename",
",",
"drive_id",
"=",
"\"img_align_celeba.zip\"",
",",
"\"0B7EVK8r0v71pZjFTYXZWM3FlRnM\"",
"save_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"image_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"data_dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"image_path",
")",
":",
"logging",
".",
"info",
"(",
"'[*] {} already exists'",
".",
"format",
"(",
"save_path",
")",
")",
"else",
":",
"exists_or_mkdir",
"(",
"path",
")",
"download_file_from_google_drive",
"(",
"drive_id",
",",
"save_path",
")",
"zip_dir",
"=",
"''",
"with",
"zipfile",
".",
"ZipFile",
"(",
"save_path",
")",
"as",
"zf",
":",
"zip_dir",
"=",
"zf",
".",
"namelist",
"(",
")",
"[",
"0",
"]",
"zf",
".",
"extractall",
"(",
"path",
")",
"os",
".",
"remove",
"(",
"save_path",
")",
"os",
".",
"rename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"zip_dir",
")",
",",
"image_path",
")",
"data_files",
"=",
"load_file_list",
"(",
"path",
"=",
"image_path",
",",
"regx",
"=",
"'\\\\.jpg'",
",",
"printable",
"=",
"False",
")",
"for",
"i",
",",
"_v",
"in",
"enumerate",
"(",
"data_files",
")",
":",
"data_files",
"[",
"i",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"image_path",
",",
"data_files",
"[",
"i",
"]",
")",
"return",
"data_files"
] | Load CelebA dataset
Return a list of image path.
Parameters
-----------
path : str
The path that the data is downloaded to, defaults is ``data/celebA/``. | [
"Load",
"CelebA",
"dataset"
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L977-L1007 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | save_npz | def save_npz(save_list=None, name='model.npz', sess=None):
"""Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore.
Parameters
----------
save_list : list of tensor
A list of parameters (tensor) to be saved.
name : str
The name of the `.npz` file.
sess : None or Session
Session may be required in some case.
Examples
--------
Save model to npz
>>> tl.files.save_npz(network.all_params, name='model.npz', sess=sess)
Load model from npz (Method 1)
>>> load_params = tl.files.load_npz(name='model.npz')
>>> tl.files.assign_params(sess, load_params, network)
Load model from npz (Method 2)
>>> tl.files.load_and_assign_npz(sess=sess, name='model.npz', network=network)
Notes
-----
If you got session issues, you can change the value.eval() to value.eval(session=sess)
References
----------
`Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__
"""
logging.info("[*] Saving TL params into %s" % name)
if save_list is None:
save_list = []
save_list_var = []
if sess:
save_list_var = sess.run(save_list)
else:
try:
save_list_var.extend([v.eval() for v in save_list])
except Exception:
logging.info(
" Fail to save model, Hint: pass the session into this function, tl.files.save_npz(network.all_params, name='model.npz', sess=sess)"
)
np.savez(name, params=save_list_var)
save_list_var = None
del save_list_var
logging.info("[*] Saved") | python | def save_npz(save_list=None, name='model.npz', sess=None):
"""Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore.
Parameters
----------
save_list : list of tensor
A list of parameters (tensor) to be saved.
name : str
The name of the `.npz` file.
sess : None or Session
Session may be required in some case.
Examples
--------
Save model to npz
>>> tl.files.save_npz(network.all_params, name='model.npz', sess=sess)
Load model from npz (Method 1)
>>> load_params = tl.files.load_npz(name='model.npz')
>>> tl.files.assign_params(sess, load_params, network)
Load model from npz (Method 2)
>>> tl.files.load_and_assign_npz(sess=sess, name='model.npz', network=network)
Notes
-----
If you got session issues, you can change the value.eval() to value.eval(session=sess)
References
----------
`Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__
"""
logging.info("[*] Saving TL params into %s" % name)
if save_list is None:
save_list = []
save_list_var = []
if sess:
save_list_var = sess.run(save_list)
else:
try:
save_list_var.extend([v.eval() for v in save_list])
except Exception:
logging.info(
" Fail to save model, Hint: pass the session into this function, tl.files.save_npz(network.all_params, name='model.npz', sess=sess)"
)
np.savez(name, params=save_list_var)
save_list_var = None
del save_list_var
logging.info("[*] Saved") | [
"def",
"save_npz",
"(",
"save_list",
"=",
"None",
",",
"name",
"=",
"'model.npz'",
",",
"sess",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"\"[*] Saving TL params into %s\"",
"%",
"name",
")",
"if",
"save_list",
"is",
"None",
":",
"save_list",
"=",
"[",
"]",
"save_list_var",
"=",
"[",
"]",
"if",
"sess",
":",
"save_list_var",
"=",
"sess",
".",
"run",
"(",
"save_list",
")",
"else",
":",
"try",
":",
"save_list_var",
".",
"extend",
"(",
"[",
"v",
".",
"eval",
"(",
")",
"for",
"v",
"in",
"save_list",
"]",
")",
"except",
"Exception",
":",
"logging",
".",
"info",
"(",
"\" Fail to save model, Hint: pass the session into this function, tl.files.save_npz(network.all_params, name='model.npz', sess=sess)\"",
")",
"np",
".",
"savez",
"(",
"name",
",",
"params",
"=",
"save_list_var",
")",
"save_list_var",
"=",
"None",
"del",
"save_list_var",
"logging",
".",
"info",
"(",
"\"[*] Saved\"",
")"
] | Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore.
Parameters
----------
save_list : list of tensor
A list of parameters (tensor) to be saved.
name : str
The name of the `.npz` file.
sess : None or Session
Session may be required in some case.
Examples
--------
Save model to npz
>>> tl.files.save_npz(network.all_params, name='model.npz', sess=sess)
Load model from npz (Method 1)
>>> load_params = tl.files.load_npz(name='model.npz')
>>> tl.files.assign_params(sess, load_params, network)
Load model from npz (Method 2)
>>> tl.files.load_and_assign_npz(sess=sess, name='model.npz', network=network)
Notes
-----
If you got session issues, you can change the value.eval() to value.eval(session=sess)
References
----------
`Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__ | [
"Input",
"parameters",
"and",
"the",
"file",
"name",
"save",
"parameters",
"into",
".",
"npz",
"file",
".",
"Use",
"tl",
".",
"utils",
".",
"load_npz",
"()",
"to",
"restore",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1568-L1621 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_npz | def load_npz(path='', name='model.npz'):
"""Load the parameters of a Model saved by tl.files.save_npz().
Parameters
----------
path : str
Folder path to `.npz` file.
name : str
The name of the `.npz` file.
Returns
--------
list of array
A list of parameters in order.
Examples
--------
- See ``tl.files.save_npz``
References
----------
- `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__
"""
d = np.load(os.path.join(path, name))
return d['params'] | python | def load_npz(path='', name='model.npz'):
"""Load the parameters of a Model saved by tl.files.save_npz().
Parameters
----------
path : str
Folder path to `.npz` file.
name : str
The name of the `.npz` file.
Returns
--------
list of array
A list of parameters in order.
Examples
--------
- See ``tl.files.save_npz``
References
----------
- `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__
"""
d = np.load(os.path.join(path, name))
return d['params'] | [
"def",
"load_npz",
"(",
"path",
"=",
"''",
",",
"name",
"=",
"'model.npz'",
")",
":",
"d",
"=",
"np",
".",
"load",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
")",
"return",
"d",
"[",
"'params'",
"]"
] | Load the parameters of a Model saved by tl.files.save_npz().
Parameters
----------
path : str
Folder path to `.npz` file.
name : str
The name of the `.npz` file.
Returns
--------
list of array
A list of parameters in order.
Examples
--------
- See ``tl.files.save_npz``
References
----------
- `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`__ | [
"Load",
"the",
"parameters",
"of",
"a",
"Model",
"saved",
"by",
"tl",
".",
"files",
".",
"save_npz",
"()",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1624-L1649 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | assign_params | def assign_params(sess, params, network):
"""Assign the given parameters to the TensorLayer network.
Parameters
----------
sess : Session
TensorFlow Session.
params : list of array
A list of parameters (array) in order.
network : :class:`Layer`
The network to be assigned.
Returns
--------
list of operations
A list of tf ops in order that assign params. Support sess.run(ops) manually.
Examples
--------
- See ``tl.files.save_npz``
References
----------
- `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__
"""
ops = []
for idx, param in enumerate(params):
ops.append(network.all_params[idx].assign(param))
if sess is not None:
sess.run(ops)
return ops | python | def assign_params(sess, params, network):
"""Assign the given parameters to the TensorLayer network.
Parameters
----------
sess : Session
TensorFlow Session.
params : list of array
A list of parameters (array) in order.
network : :class:`Layer`
The network to be assigned.
Returns
--------
list of operations
A list of tf ops in order that assign params. Support sess.run(ops) manually.
Examples
--------
- See ``tl.files.save_npz``
References
----------
- `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__
"""
ops = []
for idx, param in enumerate(params):
ops.append(network.all_params[idx].assign(param))
if sess is not None:
sess.run(ops)
return ops | [
"def",
"assign_params",
"(",
"sess",
",",
"params",
",",
"network",
")",
":",
"ops",
"=",
"[",
"]",
"for",
"idx",
",",
"param",
"in",
"enumerate",
"(",
"params",
")",
":",
"ops",
".",
"append",
"(",
"network",
".",
"all_params",
"[",
"idx",
"]",
".",
"assign",
"(",
"param",
")",
")",
"if",
"sess",
"is",
"not",
"None",
":",
"sess",
".",
"run",
"(",
"ops",
")",
"return",
"ops"
] | Assign the given parameters to the TensorLayer network.
Parameters
----------
sess : Session
TensorFlow Session.
params : list of array
A list of parameters (array) in order.
network : :class:`Layer`
The network to be assigned.
Returns
--------
list of operations
A list of tf ops in order that assign params. Support sess.run(ops) manually.
Examples
--------
- See ``tl.files.save_npz``
References
----------
- `Assign value to a TensorFlow variable <http://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable>`__ | [
"Assign",
"the",
"given",
"parameters",
"to",
"the",
"TensorLayer",
"network",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1652-L1683 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_and_assign_npz | def load_and_assign_npz(sess=None, name=None, network=None):
"""Load model from npz and assign to a network.
Parameters
-------------
sess : Session
TensorFlow Session.
name : str
The name of the `.npz` file.
network : :class:`Layer`
The network to be assigned.
Returns
--------
False or network
Returns False, if the model is not exist.
Examples
--------
- See ``tl.files.save_npz``
"""
if network is None:
raise ValueError("network is None.")
if sess is None:
raise ValueError("session is None.")
if not os.path.exists(name):
logging.error("file {} doesn't exist.".format(name))
return False
else:
params = load_npz(name=name)
assign_params(sess, params, network)
logging.info("[*] Load {} SUCCESS!".format(name))
return network | python | def load_and_assign_npz(sess=None, name=None, network=None):
"""Load model from npz and assign to a network.
Parameters
-------------
sess : Session
TensorFlow Session.
name : str
The name of the `.npz` file.
network : :class:`Layer`
The network to be assigned.
Returns
--------
False or network
Returns False, if the model is not exist.
Examples
--------
- See ``tl.files.save_npz``
"""
if network is None:
raise ValueError("network is None.")
if sess is None:
raise ValueError("session is None.")
if not os.path.exists(name):
logging.error("file {} doesn't exist.".format(name))
return False
else:
params = load_npz(name=name)
assign_params(sess, params, network)
logging.info("[*] Load {} SUCCESS!".format(name))
return network | [
"def",
"load_and_assign_npz",
"(",
"sess",
"=",
"None",
",",
"name",
"=",
"None",
",",
"network",
"=",
"None",
")",
":",
"if",
"network",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"network is None.\"",
")",
"if",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"session is None.\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"logging",
".",
"error",
"(",
"\"file {} doesn't exist.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"False",
"else",
":",
"params",
"=",
"load_npz",
"(",
"name",
"=",
"name",
")",
"assign_params",
"(",
"sess",
",",
"params",
",",
"network",
")",
"logging",
".",
"info",
"(",
"\"[*] Load {} SUCCESS!\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"network"
] | Load model from npz and assign to a network.
Parameters
-------------
sess : Session
TensorFlow Session.
name : str
The name of the `.npz` file.
network : :class:`Layer`
The network to be assigned.
Returns
--------
False or network
Returns False, if the model is not exist.
Examples
--------
- See ``tl.files.save_npz`` | [
"Load",
"model",
"from",
"npz",
"and",
"assign",
"to",
"a",
"network",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1686-L1719 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | save_npz_dict | def save_npz_dict(save_list=None, name='model.npz', sess=None):
"""Input parameters and the file name, save parameters as a dictionary into .npz file.
Use ``tl.files.load_and_assign_npz_dict()`` to restore.
Parameters
----------
save_list : list of parameters
A list of parameters (tensor) to be saved.
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Session.
"""
if sess is None:
raise ValueError("session is None.")
if save_list is None:
save_list = []
save_list_names = [tensor.name for tensor in save_list]
save_list_var = sess.run(save_list)
save_var_dict = {save_list_names[idx]: val for idx, val in enumerate(save_list_var)}
np.savez(name, **save_var_dict)
save_list_var = None
save_var_dict = None
del save_list_var
del save_var_dict
logging.info("[*] Model saved in npz_dict %s" % name) | python | def save_npz_dict(save_list=None, name='model.npz', sess=None):
"""Input parameters and the file name, save parameters as a dictionary into .npz file.
Use ``tl.files.load_and_assign_npz_dict()`` to restore.
Parameters
----------
save_list : list of parameters
A list of parameters (tensor) to be saved.
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Session.
"""
if sess is None:
raise ValueError("session is None.")
if save_list is None:
save_list = []
save_list_names = [tensor.name for tensor in save_list]
save_list_var = sess.run(save_list)
save_var_dict = {save_list_names[idx]: val for idx, val in enumerate(save_list_var)}
np.savez(name, **save_var_dict)
save_list_var = None
save_var_dict = None
del save_list_var
del save_var_dict
logging.info("[*] Model saved in npz_dict %s" % name) | [
"def",
"save_npz_dict",
"(",
"save_list",
"=",
"None",
",",
"name",
"=",
"'model.npz'",
",",
"sess",
"=",
"None",
")",
":",
"if",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"session is None.\"",
")",
"if",
"save_list",
"is",
"None",
":",
"save_list",
"=",
"[",
"]",
"save_list_names",
"=",
"[",
"tensor",
".",
"name",
"for",
"tensor",
"in",
"save_list",
"]",
"save_list_var",
"=",
"sess",
".",
"run",
"(",
"save_list",
")",
"save_var_dict",
"=",
"{",
"save_list_names",
"[",
"idx",
"]",
":",
"val",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"save_list_var",
")",
"}",
"np",
".",
"savez",
"(",
"name",
",",
"*",
"*",
"save_var_dict",
")",
"save_list_var",
"=",
"None",
"save_var_dict",
"=",
"None",
"del",
"save_list_var",
"del",
"save_var_dict",
"logging",
".",
"info",
"(",
"\"[*] Model saved in npz_dict %s\"",
"%",
"name",
")"
] | Input parameters and the file name, save parameters as a dictionary into .npz file.
Use ``tl.files.load_and_assign_npz_dict()`` to restore.
Parameters
----------
save_list : list of parameters
A list of parameters (tensor) to be saved.
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Session. | [
"Input",
"parameters",
"and",
"the",
"file",
"name",
"save",
"parameters",
"as",
"a",
"dictionary",
"into",
".",
"npz",
"file",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1722-L1750 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_and_assign_npz_dict | def load_and_assign_npz_dict(name='model.npz', sess=None):
"""Restore the parameters saved by ``tl.files.save_npz_dict()``.
Parameters
----------
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Session.
"""
if sess is None:
raise ValueError("session is None.")
if not os.path.exists(name):
logging.error("file {} doesn't exist.".format(name))
return False
params = np.load(name)
if len(params.keys()) != len(set(params.keys())):
raise Exception("Duplication in model npz_dict %s" % name)
ops = list()
for key in params.keys():
try:
# tensor = tf.get_default_graph().get_tensor_by_name(key)
# varlist = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=key)
varlist = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=key)
if len(varlist) > 1:
raise Exception("[!] Multiple candidate variables to be assigned for name %s" % key)
elif len(varlist) == 0:
raise KeyError
else:
ops.append(varlist[0].assign(params[key]))
logging.info("[*] params restored: %s" % key)
except KeyError:
logging.info("[!] Warning: Tensor named %s not found in network." % key)
sess.run(ops)
logging.info("[*] Model restored from npz_dict %s" % name) | python | def load_and_assign_npz_dict(name='model.npz', sess=None):
"""Restore the parameters saved by ``tl.files.save_npz_dict()``.
Parameters
----------
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Session.
"""
if sess is None:
raise ValueError("session is None.")
if not os.path.exists(name):
logging.error("file {} doesn't exist.".format(name))
return False
params = np.load(name)
if len(params.keys()) != len(set(params.keys())):
raise Exception("Duplication in model npz_dict %s" % name)
ops = list()
for key in params.keys():
try:
# tensor = tf.get_default_graph().get_tensor_by_name(key)
# varlist = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=key)
varlist = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=key)
if len(varlist) > 1:
raise Exception("[!] Multiple candidate variables to be assigned for name %s" % key)
elif len(varlist) == 0:
raise KeyError
else:
ops.append(varlist[0].assign(params[key]))
logging.info("[*] params restored: %s" % key)
except KeyError:
logging.info("[!] Warning: Tensor named %s not found in network." % key)
sess.run(ops)
logging.info("[*] Model restored from npz_dict %s" % name) | [
"def",
"load_and_assign_npz_dict",
"(",
"name",
"=",
"'model.npz'",
",",
"sess",
"=",
"None",
")",
":",
"if",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"session is None.\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"logging",
".",
"error",
"(",
"\"file {} doesn't exist.\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"False",
"params",
"=",
"np",
".",
"load",
"(",
"name",
")",
"if",
"len",
"(",
"params",
".",
"keys",
"(",
")",
")",
"!=",
"len",
"(",
"set",
"(",
"params",
".",
"keys",
"(",
")",
")",
")",
":",
"raise",
"Exception",
"(",
"\"Duplication in model npz_dict %s\"",
"%",
"name",
")",
"ops",
"=",
"list",
"(",
")",
"for",
"key",
"in",
"params",
".",
"keys",
"(",
")",
":",
"try",
":",
"# tensor = tf.get_default_graph().get_tensor_by_name(key)",
"# varlist = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=key)",
"varlist",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"GLOBAL_VARIABLES",
",",
"scope",
"=",
"key",
")",
"if",
"len",
"(",
"varlist",
")",
">",
"1",
":",
"raise",
"Exception",
"(",
"\"[!] Multiple candidate variables to be assigned for name %s\"",
"%",
"key",
")",
"elif",
"len",
"(",
"varlist",
")",
"==",
"0",
":",
"raise",
"KeyError",
"else",
":",
"ops",
".",
"append",
"(",
"varlist",
"[",
"0",
"]",
".",
"assign",
"(",
"params",
"[",
"key",
"]",
")",
")",
"logging",
".",
"info",
"(",
"\"[*] params restored: %s\"",
"%",
"key",
")",
"except",
"KeyError",
":",
"logging",
".",
"info",
"(",
"\"[!] Warning: Tensor named %s not found in network.\"",
"%",
"key",
")",
"sess",
".",
"run",
"(",
"ops",
")",
"logging",
".",
"info",
"(",
"\"[*] Model restored from npz_dict %s\"",
"%",
"name",
")"
] | Restore the parameters saved by ``tl.files.save_npz_dict()``.
Parameters
----------
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Session. | [
"Restore",
"the",
"parameters",
"saved",
"by",
"tl",
".",
"files",
".",
"save_npz_dict",
"()",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1753-L1791 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | save_ckpt | def save_ckpt(
sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, global_step=None, printable=False
):
"""Save parameters into `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``model.ckpt``.
save_dir : str
The path / file directory to the `ckpt`, default is ``checkpoint``.
var_list : list of tensor
The parameters / variables (tensor) to be saved. If empty, save all global variables (default).
global_step : int or None
Step number.
printable : boolean
Whether to print all parameters information.
See Also
--------
load_ckpt
"""
if sess is None:
raise ValueError("session is None.")
if var_list is None:
var_list = []
ckpt_file = os.path.join(save_dir, mode_name)
if var_list == []:
var_list = tf.global_variables()
logging.info("[*] save %s n_params: %d" % (ckpt_file, len(var_list)))
if printable:
for idx, v in enumerate(var_list):
logging.info(" param {:3}: {:15} {}".format(idx, v.name, str(v.get_shape())))
saver = tf.train.Saver(var_list)
saver.save(sess, ckpt_file, global_step=global_step) | python | def save_ckpt(
sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, global_step=None, printable=False
):
"""Save parameters into `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``model.ckpt``.
save_dir : str
The path / file directory to the `ckpt`, default is ``checkpoint``.
var_list : list of tensor
The parameters / variables (tensor) to be saved. If empty, save all global variables (default).
global_step : int or None
Step number.
printable : boolean
Whether to print all parameters information.
See Also
--------
load_ckpt
"""
if sess is None:
raise ValueError("session is None.")
if var_list is None:
var_list = []
ckpt_file = os.path.join(save_dir, mode_name)
if var_list == []:
var_list = tf.global_variables()
logging.info("[*] save %s n_params: %d" % (ckpt_file, len(var_list)))
if printable:
for idx, v in enumerate(var_list):
logging.info(" param {:3}: {:15} {}".format(idx, v.name, str(v.get_shape())))
saver = tf.train.Saver(var_list)
saver.save(sess, ckpt_file, global_step=global_step) | [
"def",
"save_ckpt",
"(",
"sess",
"=",
"None",
",",
"mode_name",
"=",
"'model.ckpt'",
",",
"save_dir",
"=",
"'checkpoint'",
",",
"var_list",
"=",
"None",
",",
"global_step",
"=",
"None",
",",
"printable",
"=",
"False",
")",
":",
"if",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"session is None.\"",
")",
"if",
"var_list",
"is",
"None",
":",
"var_list",
"=",
"[",
"]",
"ckpt_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"save_dir",
",",
"mode_name",
")",
"if",
"var_list",
"==",
"[",
"]",
":",
"var_list",
"=",
"tf",
".",
"global_variables",
"(",
")",
"logging",
".",
"info",
"(",
"\"[*] save %s n_params: %d\"",
"%",
"(",
"ckpt_file",
",",
"len",
"(",
"var_list",
")",
")",
")",
"if",
"printable",
":",
"for",
"idx",
",",
"v",
"in",
"enumerate",
"(",
"var_list",
")",
":",
"logging",
".",
"info",
"(",
"\" param {:3}: {:15} {}\"",
".",
"format",
"(",
"idx",
",",
"v",
".",
"name",
",",
"str",
"(",
"v",
".",
"get_shape",
"(",
")",
")",
")",
")",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
"var_list",
")",
"saver",
".",
"save",
"(",
"sess",
",",
"ckpt_file",
",",
"global_step",
"=",
"global_step",
")"
] | Save parameters into `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``model.ckpt``.
save_dir : str
The path / file directory to the `ckpt`, default is ``checkpoint``.
var_list : list of tensor
The parameters / variables (tensor) to be saved. If empty, save all global variables (default).
global_step : int or None
Step number.
printable : boolean
Whether to print all parameters information.
See Also
--------
load_ckpt | [
"Save",
"parameters",
"into",
"ckpt",
"file",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1794-L1835 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_ckpt | def load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, is_latest=True, printable=False):
"""Load parameters from `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``model.ckpt``.
save_dir : str
The path / file directory to the `ckpt`, default is ``checkpoint``.
var_list : list of tensor
The parameters / variables (tensor) to be saved. If empty, save all global variables (default).
is_latest : boolean
Whether to load the latest `ckpt`, if False, load the `ckpt` with the name of ```mode_name``.
printable : boolean
Whether to print all parameters information.
Examples
----------
- Save all global parameters.
>>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', save_dir='model', printable=True)
- Save specific parameters.
>>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', printable=True)
- Load latest ckpt.
>>> tl.files.load_ckpt(sess=sess, var_list=net.all_params, save_dir='model', printable=True)
- Load specific ckpt.
>>> tl.files.load_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', is_latest=False, printable=True)
"""
if sess is None:
raise ValueError("session is None.")
if var_list is None:
var_list = []
if is_latest:
ckpt_file = tf.train.latest_checkpoint(save_dir)
else:
ckpt_file = os.path.join(save_dir, mode_name)
if not var_list:
var_list = tf.global_variables()
logging.info("[*] load %s n_params: %d" % (ckpt_file, len(var_list)))
if printable:
for idx, v in enumerate(var_list):
logging.info(" param {:3}: {:15} {}".format(idx, v.name, str(v.get_shape())))
try:
saver = tf.train.Saver(var_list)
saver.restore(sess, ckpt_file)
except Exception as e:
logging.info(e)
logging.info("[*] load ckpt fail ...") | python | def load_ckpt(sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, is_latest=True, printable=False):
"""Load parameters from `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``model.ckpt``.
save_dir : str
The path / file directory to the `ckpt`, default is ``checkpoint``.
var_list : list of tensor
The parameters / variables (tensor) to be saved. If empty, save all global variables (default).
is_latest : boolean
Whether to load the latest `ckpt`, if False, load the `ckpt` with the name of ```mode_name``.
printable : boolean
Whether to print all parameters information.
Examples
----------
- Save all global parameters.
>>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', save_dir='model', printable=True)
- Save specific parameters.
>>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', printable=True)
- Load latest ckpt.
>>> tl.files.load_ckpt(sess=sess, var_list=net.all_params, save_dir='model', printable=True)
- Load specific ckpt.
>>> tl.files.load_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', is_latest=False, printable=True)
"""
if sess is None:
raise ValueError("session is None.")
if var_list is None:
var_list = []
if is_latest:
ckpt_file = tf.train.latest_checkpoint(save_dir)
else:
ckpt_file = os.path.join(save_dir, mode_name)
if not var_list:
var_list = tf.global_variables()
logging.info("[*] load %s n_params: %d" % (ckpt_file, len(var_list)))
if printable:
for idx, v in enumerate(var_list):
logging.info(" param {:3}: {:15} {}".format(idx, v.name, str(v.get_shape())))
try:
saver = tf.train.Saver(var_list)
saver.restore(sess, ckpt_file)
except Exception as e:
logging.info(e)
logging.info("[*] load ckpt fail ...") | [
"def",
"load_ckpt",
"(",
"sess",
"=",
"None",
",",
"mode_name",
"=",
"'model.ckpt'",
",",
"save_dir",
"=",
"'checkpoint'",
",",
"var_list",
"=",
"None",
",",
"is_latest",
"=",
"True",
",",
"printable",
"=",
"False",
")",
":",
"if",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"session is None.\"",
")",
"if",
"var_list",
"is",
"None",
":",
"var_list",
"=",
"[",
"]",
"if",
"is_latest",
":",
"ckpt_file",
"=",
"tf",
".",
"train",
".",
"latest_checkpoint",
"(",
"save_dir",
")",
"else",
":",
"ckpt_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"save_dir",
",",
"mode_name",
")",
"if",
"not",
"var_list",
":",
"var_list",
"=",
"tf",
".",
"global_variables",
"(",
")",
"logging",
".",
"info",
"(",
"\"[*] load %s n_params: %d\"",
"%",
"(",
"ckpt_file",
",",
"len",
"(",
"var_list",
")",
")",
")",
"if",
"printable",
":",
"for",
"idx",
",",
"v",
"in",
"enumerate",
"(",
"var_list",
")",
":",
"logging",
".",
"info",
"(",
"\" param {:3}: {:15} {}\"",
".",
"format",
"(",
"idx",
",",
"v",
".",
"name",
",",
"str",
"(",
"v",
".",
"get_shape",
"(",
")",
")",
")",
")",
"try",
":",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
"var_list",
")",
"saver",
".",
"restore",
"(",
"sess",
",",
"ckpt_file",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"info",
"(",
"e",
")",
"logging",
".",
"info",
"(",
"\"[*] load ckpt fail ...\"",
")"
] | Load parameters from `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``model.ckpt``.
save_dir : str
The path / file directory to the `ckpt`, default is ``checkpoint``.
var_list : list of tensor
The parameters / variables (tensor) to be saved. If empty, save all global variables (default).
is_latest : boolean
Whether to load the latest `ckpt`, if False, load the `ckpt` with the name of ```mode_name``.
printable : boolean
Whether to print all parameters information.
Examples
----------
- Save all global parameters.
>>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', save_dir='model', printable=True)
- Save specific parameters.
>>> tl.files.save_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', printable=True)
- Load latest ckpt.
>>> tl.files.load_ckpt(sess=sess, var_list=net.all_params, save_dir='model', printable=True)
- Load specific ckpt.
>>> tl.files.load_ckpt(sess=sess, mode_name='model.ckpt', var_list=net.all_params, save_dir='model', is_latest=False, printable=True) | [
"Load",
"parameters",
"from",
"ckpt",
"file",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L1838-L1899 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_npy_to_any | def load_npy_to_any(path='', name='file.npy'):
"""Load `.npy` file.
Parameters
------------
path : str
Path to the file (optional).
name : str
File name.
Examples
---------
- see tl.files.save_any_to_npy()
"""
file_path = os.path.join(path, name)
try:
return np.load(file_path).item()
except Exception:
return np.load(file_path)
raise Exception("[!] Fail to load %s" % file_path) | python | def load_npy_to_any(path='', name='file.npy'):
"""Load `.npy` file.
Parameters
------------
path : str
Path to the file (optional).
name : str
File name.
Examples
---------
- see tl.files.save_any_to_npy()
"""
file_path = os.path.join(path, name)
try:
return np.load(file_path).item()
except Exception:
return np.load(file_path)
raise Exception("[!] Fail to load %s" % file_path) | [
"def",
"load_npy_to_any",
"(",
"path",
"=",
"''",
",",
"name",
"=",
"'file.npy'",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"try",
":",
"return",
"np",
".",
"load",
"(",
"file_path",
")",
".",
"item",
"(",
")",
"except",
"Exception",
":",
"return",
"np",
".",
"load",
"(",
"file_path",
")",
"raise",
"Exception",
"(",
"\"[!] Fail to load %s\"",
"%",
"file_path",
")"
] | Load `.npy` file.
Parameters
------------
path : str
Path to the file (optional).
name : str
File name.
Examples
---------
- see tl.files.save_any_to_npy() | [
"Load",
".",
"npy",
"file",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2093-L2113 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_file_list | def load_file_list(path=None, regx='\.jpg', printable=True, keep_prefix=False):
r"""Return a file list in a folder by given a path and regular expression.
Parameters
----------
path : str or None
A folder path, if `None`, use the current directory.
regx : str
The regx of file name.
printable : boolean
Whether to print the files infomation.
keep_prefix : boolean
Whether to keep path in the file name.
Examples
----------
>>> file_list = tl.files.load_file_list(path=None, regx='w1pre_[0-9]+\.(npz)')
"""
if path is None:
path = os.getcwd()
file_list = os.listdir(path)
return_list = []
for _, f in enumerate(file_list):
if re.search(regx, f):
return_list.append(f)
# return_list.sort()
if keep_prefix:
for i, f in enumerate(return_list):
return_list[i] = os.path.join(path, f)
if printable:
logging.info('Match file list = %s' % return_list)
logging.info('Number of files = %d' % len(return_list))
return return_list | python | def load_file_list(path=None, regx='\.jpg', printable=True, keep_prefix=False):
r"""Return a file list in a folder by given a path and regular expression.
Parameters
----------
path : str or None
A folder path, if `None`, use the current directory.
regx : str
The regx of file name.
printable : boolean
Whether to print the files infomation.
keep_prefix : boolean
Whether to keep path in the file name.
Examples
----------
>>> file_list = tl.files.load_file_list(path=None, regx='w1pre_[0-9]+\.(npz)')
"""
if path is None:
path = os.getcwd()
file_list = os.listdir(path)
return_list = []
for _, f in enumerate(file_list):
if re.search(regx, f):
return_list.append(f)
# return_list.sort()
if keep_prefix:
for i, f in enumerate(return_list):
return_list[i] = os.path.join(path, f)
if printable:
logging.info('Match file list = %s' % return_list)
logging.info('Number of files = %d' % len(return_list))
return return_list | [
"def",
"load_file_list",
"(",
"path",
"=",
"None",
",",
"regx",
"=",
"'\\.jpg'",
",",
"printable",
"=",
"True",
",",
"keep_prefix",
"=",
"False",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"file_list",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"return_list",
"=",
"[",
"]",
"for",
"_",
",",
"f",
"in",
"enumerate",
"(",
"file_list",
")",
":",
"if",
"re",
".",
"search",
"(",
"regx",
",",
"f",
")",
":",
"return_list",
".",
"append",
"(",
"f",
")",
"# return_list.sort()",
"if",
"keep_prefix",
":",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"return_list",
")",
":",
"return_list",
"[",
"i",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",
"if",
"printable",
":",
"logging",
".",
"info",
"(",
"'Match file list = %s'",
"%",
"return_list",
")",
"logging",
".",
"info",
"(",
"'Number of files = %d'",
"%",
"len",
"(",
"return_list",
")",
")",
"return",
"return_list"
] | r"""Return a file list in a folder by given a path and regular expression.
Parameters
----------
path : str or None
A folder path, if `None`, use the current directory.
regx : str
The regx of file name.
printable : boolean
Whether to print the files infomation.
keep_prefix : boolean
Whether to keep path in the file name.
Examples
----------
>>> file_list = tl.files.load_file_list(path=None, regx='w1pre_[0-9]+\.(npz)') | [
"r",
"Return",
"a",
"file",
"list",
"in",
"a",
"folder",
"by",
"given",
"a",
"path",
"and",
"regular",
"expression",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2148-L2182 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | load_folder_list | def load_folder_list(path=""):
"""Return a folder list in a folder by given a folder path.
Parameters
----------
path : str
A folder path.
"""
return [os.path.join(path, o) for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))] | python | def load_folder_list(path=""):
"""Return a folder list in a folder by given a folder path.
Parameters
----------
path : str
A folder path.
"""
return [os.path.join(path, o) for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))] | [
"def",
"load_folder_list",
"(",
"path",
"=",
"\"\"",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"o",
")",
"for",
"o",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"o",
")",
")",
"]"
] | Return a folder list in a folder by given a folder path.
Parameters
----------
path : str
A folder path. | [
"Return",
"a",
"folder",
"list",
"in",
"a",
"folder",
"by",
"given",
"a",
"folder",
"path",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2185-L2194 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | exists_or_mkdir | def exists_or_mkdir(path, verbose=True):
"""Check a folder by given name, if not exist, create the folder and return False,
if directory exists, return True.
Parameters
----------
path : str
A folder path.
verbose : boolean
If True (default), prints results.
Returns
--------
boolean
True if folder already exist, otherwise, returns False and create the folder.
Examples
--------
>>> tl.files.exists_or_mkdir("checkpoints/train")
"""
if not os.path.exists(path):
if verbose:
logging.info("[*] creates %s ..." % path)
os.makedirs(path)
return False
else:
if verbose:
logging.info("[!] %s exists ..." % path)
return True | python | def exists_or_mkdir(path, verbose=True):
"""Check a folder by given name, if not exist, create the folder and return False,
if directory exists, return True.
Parameters
----------
path : str
A folder path.
verbose : boolean
If True (default), prints results.
Returns
--------
boolean
True if folder already exist, otherwise, returns False and create the folder.
Examples
--------
>>> tl.files.exists_or_mkdir("checkpoints/train")
"""
if not os.path.exists(path):
if verbose:
logging.info("[*] creates %s ..." % path)
os.makedirs(path)
return False
else:
if verbose:
logging.info("[!] %s exists ..." % path)
return True | [
"def",
"exists_or_mkdir",
"(",
"path",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"verbose",
":",
"logging",
".",
"info",
"(",
"\"[*] creates %s ...\"",
"%",
"path",
")",
"os",
".",
"makedirs",
"(",
"path",
")",
"return",
"False",
"else",
":",
"if",
"verbose",
":",
"logging",
".",
"info",
"(",
"\"[!] %s exists ...\"",
"%",
"path",
")",
"return",
"True"
] | Check a folder by given name, if not exist, create the folder and return False,
if directory exists, return True.
Parameters
----------
path : str
A folder path.
verbose : boolean
If True (default), prints results.
Returns
--------
boolean
True if folder already exist, otherwise, returns False and create the folder.
Examples
--------
>>> tl.files.exists_or_mkdir("checkpoints/train") | [
"Check",
"a",
"folder",
"by",
"given",
"name",
"if",
"not",
"exist",
"create",
"the",
"folder",
"and",
"return",
"False",
"if",
"directory",
"exists",
"return",
"True",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2197-L2226 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | maybe_download_and_extract | def maybe_download_and_extract(filename, working_directory, url_source, extract=False, expected_bytes=None):
"""Checks if file exists in working_directory otherwise tries to dowload the file,
and optionally also tries to extract the file if format is ".zip" or ".tar"
Parameters
-----------
filename : str
The name of the (to be) dowloaded file.
working_directory : str
A folder path to search for the file in and dowload the file to
url : str
The URL to download the file from
extract : boolean
If True, tries to uncompress the dowloaded file is ".tar.gz/.tar.bz2" or ".zip" file, default is False.
expected_bytes : int or None
If set tries to verify that the downloaded file is of the specified size, otherwise raises an Exception, defaults is None which corresponds to no check being performed.
Returns
----------
str
File path of the dowloaded (uncompressed) file.
Examples
--------
>>> down_file = tl.files.maybe_download_and_extract(filename='train-images-idx3-ubyte.gz',
... working_directory='data/',
... url_source='http://yann.lecun.com/exdb/mnist/')
>>> tl.files.maybe_download_and_extract(filename='ADEChallengeData2016.zip',
... working_directory='data/',
... url_source='http://sceneparsing.csail.mit.edu/data/',
... extract=True)
"""
# We first define a download function, supporting both Python 2 and 3.
def _download(filename, working_directory, url_source):
progress_bar = progressbar.ProgressBar()
def _dlProgress(count, blockSize, totalSize, pbar=progress_bar):
if (totalSize != 0):
if not pbar.max_value:
totalBlocks = math.ceil(float(totalSize) / float(blockSize))
pbar.max_value = int(totalBlocks)
pbar.update(count, force=True)
filepath = os.path.join(working_directory, filename)
logging.info('Downloading %s...\n' % filename)
urlretrieve(url_source + filename, filepath, reporthook=_dlProgress)
exists_or_mkdir(working_directory, verbose=False)
filepath = os.path.join(working_directory, filename)
if not os.path.exists(filepath):
_download(filename, working_directory, url_source)
statinfo = os.stat(filepath)
logging.info('Succesfully downloaded %s %s bytes.' % (filename, statinfo.st_size)) # , 'bytes.')
if (not (expected_bytes is None) and (expected_bytes != statinfo.st_size)):
raise Exception('Failed to verify ' + filename + '. Can you get to it with a browser?')
if (extract):
if tarfile.is_tarfile(filepath):
logging.info('Trying to extract tar file')
tarfile.open(filepath, 'r').extractall(working_directory)
logging.info('... Success!')
elif zipfile.is_zipfile(filepath):
logging.info('Trying to extract zip file')
with zipfile.ZipFile(filepath) as zf:
zf.extractall(working_directory)
logging.info('... Success!')
else:
logging.info("Unknown compression_format only .tar.gz/.tar.bz2/.tar and .zip supported")
return filepath | python | def maybe_download_and_extract(filename, working_directory, url_source, extract=False, expected_bytes=None):
"""Checks if file exists in working_directory otherwise tries to dowload the file,
and optionally also tries to extract the file if format is ".zip" or ".tar"
Parameters
-----------
filename : str
The name of the (to be) dowloaded file.
working_directory : str
A folder path to search for the file in and dowload the file to
url : str
The URL to download the file from
extract : boolean
If True, tries to uncompress the dowloaded file is ".tar.gz/.tar.bz2" or ".zip" file, default is False.
expected_bytes : int or None
If set tries to verify that the downloaded file is of the specified size, otherwise raises an Exception, defaults is None which corresponds to no check being performed.
Returns
----------
str
File path of the dowloaded (uncompressed) file.
Examples
--------
>>> down_file = tl.files.maybe_download_and_extract(filename='train-images-idx3-ubyte.gz',
... working_directory='data/',
... url_source='http://yann.lecun.com/exdb/mnist/')
>>> tl.files.maybe_download_and_extract(filename='ADEChallengeData2016.zip',
... working_directory='data/',
... url_source='http://sceneparsing.csail.mit.edu/data/',
... extract=True)
"""
# We first define a download function, supporting both Python 2 and 3.
def _download(filename, working_directory, url_source):
progress_bar = progressbar.ProgressBar()
def _dlProgress(count, blockSize, totalSize, pbar=progress_bar):
if (totalSize != 0):
if not pbar.max_value:
totalBlocks = math.ceil(float(totalSize) / float(blockSize))
pbar.max_value = int(totalBlocks)
pbar.update(count, force=True)
filepath = os.path.join(working_directory, filename)
logging.info('Downloading %s...\n' % filename)
urlretrieve(url_source + filename, filepath, reporthook=_dlProgress)
exists_or_mkdir(working_directory, verbose=False)
filepath = os.path.join(working_directory, filename)
if not os.path.exists(filepath):
_download(filename, working_directory, url_source)
statinfo = os.stat(filepath)
logging.info('Succesfully downloaded %s %s bytes.' % (filename, statinfo.st_size)) # , 'bytes.')
if (not (expected_bytes is None) and (expected_bytes != statinfo.st_size)):
raise Exception('Failed to verify ' + filename + '. Can you get to it with a browser?')
if (extract):
if tarfile.is_tarfile(filepath):
logging.info('Trying to extract tar file')
tarfile.open(filepath, 'r').extractall(working_directory)
logging.info('... Success!')
elif zipfile.is_zipfile(filepath):
logging.info('Trying to extract zip file')
with zipfile.ZipFile(filepath) as zf:
zf.extractall(working_directory)
logging.info('... Success!')
else:
logging.info("Unknown compression_format only .tar.gz/.tar.bz2/.tar and .zip supported")
return filepath | [
"def",
"maybe_download_and_extract",
"(",
"filename",
",",
"working_directory",
",",
"url_source",
",",
"extract",
"=",
"False",
",",
"expected_bytes",
"=",
"None",
")",
":",
"# We first define a download function, supporting both Python 2 and 3.",
"def",
"_download",
"(",
"filename",
",",
"working_directory",
",",
"url_source",
")",
":",
"progress_bar",
"=",
"progressbar",
".",
"ProgressBar",
"(",
")",
"def",
"_dlProgress",
"(",
"count",
",",
"blockSize",
",",
"totalSize",
",",
"pbar",
"=",
"progress_bar",
")",
":",
"if",
"(",
"totalSize",
"!=",
"0",
")",
":",
"if",
"not",
"pbar",
".",
"max_value",
":",
"totalBlocks",
"=",
"math",
".",
"ceil",
"(",
"float",
"(",
"totalSize",
")",
"/",
"float",
"(",
"blockSize",
")",
")",
"pbar",
".",
"max_value",
"=",
"int",
"(",
"totalBlocks",
")",
"pbar",
".",
"update",
"(",
"count",
",",
"force",
"=",
"True",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_directory",
",",
"filename",
")",
"logging",
".",
"info",
"(",
"'Downloading %s...\\n'",
"%",
"filename",
")",
"urlretrieve",
"(",
"url_source",
"+",
"filename",
",",
"filepath",
",",
"reporthook",
"=",
"_dlProgress",
")",
"exists_or_mkdir",
"(",
"working_directory",
",",
"verbose",
"=",
"False",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_directory",
",",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
":",
"_download",
"(",
"filename",
",",
"working_directory",
",",
"url_source",
")",
"statinfo",
"=",
"os",
".",
"stat",
"(",
"filepath",
")",
"logging",
".",
"info",
"(",
"'Succesfully downloaded %s %s bytes.'",
"%",
"(",
"filename",
",",
"statinfo",
".",
"st_size",
")",
")",
"# , 'bytes.')",
"if",
"(",
"not",
"(",
"expected_bytes",
"is",
"None",
")",
"and",
"(",
"expected_bytes",
"!=",
"statinfo",
".",
"st_size",
")",
")",
":",
"raise",
"Exception",
"(",
"'Failed to verify '",
"+",
"filename",
"+",
"'. Can you get to it with a browser?'",
")",
"if",
"(",
"extract",
")",
":",
"if",
"tarfile",
".",
"is_tarfile",
"(",
"filepath",
")",
":",
"logging",
".",
"info",
"(",
"'Trying to extract tar file'",
")",
"tarfile",
".",
"open",
"(",
"filepath",
",",
"'r'",
")",
".",
"extractall",
"(",
"working_directory",
")",
"logging",
".",
"info",
"(",
"'... Success!'",
")",
"elif",
"zipfile",
".",
"is_zipfile",
"(",
"filepath",
")",
":",
"logging",
".",
"info",
"(",
"'Trying to extract zip file'",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"filepath",
")",
"as",
"zf",
":",
"zf",
".",
"extractall",
"(",
"working_directory",
")",
"logging",
".",
"info",
"(",
"'... Success!'",
")",
"else",
":",
"logging",
".",
"info",
"(",
"\"Unknown compression_format only .tar.gz/.tar.bz2/.tar and .zip supported\"",
")",
"return",
"filepath"
] | Checks if file exists in working_directory otherwise tries to dowload the file,
and optionally also tries to extract the file if format is ".zip" or ".tar"
Parameters
-----------
filename : str
The name of the (to be) dowloaded file.
working_directory : str
A folder path to search for the file in and dowload the file to
url : str
The URL to download the file from
extract : boolean
If True, tries to uncompress the dowloaded file is ".tar.gz/.tar.bz2" or ".zip" file, default is False.
expected_bytes : int or None
If set tries to verify that the downloaded file is of the specified size, otherwise raises an Exception, defaults is None which corresponds to no check being performed.
Returns
----------
str
File path of the dowloaded (uncompressed) file.
Examples
--------
>>> down_file = tl.files.maybe_download_and_extract(filename='train-images-idx3-ubyte.gz',
... working_directory='data/',
... url_source='http://yann.lecun.com/exdb/mnist/')
>>> tl.files.maybe_download_and_extract(filename='ADEChallengeData2016.zip',
... working_directory='data/',
... url_source='http://sceneparsing.csail.mit.edu/data/',
... extract=True) | [
"Checks",
"if",
"file",
"exists",
"in",
"working_directory",
"otherwise",
"tries",
"to",
"dowload",
"the",
"file",
"and",
"optionally",
"also",
"tries",
"to",
"extract",
"the",
"file",
"if",
"format",
"is",
".",
"zip",
"or",
".",
"tar"
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2229-L2305 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | natural_keys | def natural_keys(text):
"""Sort list of string with number in human order.
Examples
----------
>>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']
>>> l.sort(key=tl.files.natural_keys)
['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']
>>> l.sort() # that is what we dont want
['im03.jpg', 'im05', 'im1.jpg', 'im11.jpg', 'im21.jpg', 'im31.jpg']
References
----------
- `link <http://nedbatchelder.com/blog/200712/human_sorting.html>`__
"""
# - alist.sort(key=natural_keys) sorts in human order
# http://nedbatchelder.com/blog/200712/human_sorting.html
# (See Toothy's implementation in the comments)
def atoi(text):
return int(text) if text.isdigit() else text
return [atoi(c) for c in re.split('(\d+)', text)] | python | def natural_keys(text):
"""Sort list of string with number in human order.
Examples
----------
>>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']
>>> l.sort(key=tl.files.natural_keys)
['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']
>>> l.sort() # that is what we dont want
['im03.jpg', 'im05', 'im1.jpg', 'im11.jpg', 'im21.jpg', 'im31.jpg']
References
----------
- `link <http://nedbatchelder.com/blog/200712/human_sorting.html>`__
"""
# - alist.sort(key=natural_keys) sorts in human order
# http://nedbatchelder.com/blog/200712/human_sorting.html
# (See Toothy's implementation in the comments)
def atoi(text):
return int(text) if text.isdigit() else text
return [atoi(c) for c in re.split('(\d+)', text)] | [
"def",
"natural_keys",
"(",
"text",
")",
":",
"# - alist.sort(key=natural_keys) sorts in human order",
"# http://nedbatchelder.com/blog/200712/human_sorting.html",
"# (See Toothy's implementation in the comments)",
"def",
"atoi",
"(",
"text",
")",
":",
"return",
"int",
"(",
"text",
")",
"if",
"text",
".",
"isdigit",
"(",
")",
"else",
"text",
"return",
"[",
"atoi",
"(",
"c",
")",
"for",
"c",
"in",
"re",
".",
"split",
"(",
"'(\\d+)'",
",",
"text",
")",
"]"
] | Sort list of string with number in human order.
Examples
----------
>>> l = ['im1.jpg', 'im31.jpg', 'im11.jpg', 'im21.jpg', 'im03.jpg', 'im05.jpg']
>>> l.sort(key=tl.files.natural_keys)
['im1.jpg', 'im03.jpg', 'im05', 'im11.jpg', 'im21.jpg', 'im31.jpg']
>>> l.sort() # that is what we dont want
['im03.jpg', 'im05', 'im1.jpg', 'im11.jpg', 'im21.jpg', 'im31.jpg']
References
----------
- `link <http://nedbatchelder.com/blog/200712/human_sorting.html>`__ | [
"Sort",
"list",
"of",
"string",
"with",
"number",
"in",
"human",
"order",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2308-L2331 | valid |
tensorlayer/tensorlayer | tensorlayer/files/utils.py | npz_to_W_pdf | def npz_to_W_pdf(path=None, regx='w1pre_[0-9]+\.(npz)'):
r"""Convert the first weight matrix of `.npz` file to `.pdf` by using `tl.visualize.W()`.
Parameters
----------
path : str
A folder path to `npz` files.
regx : str
Regx for the file name.
Examples
---------
Convert the first weight matrix of w1_pre...npz file to w1_pre...pdf.
>>> tl.files.npz_to_W_pdf(path='/Users/.../npz_file/', regx='w1pre_[0-9]+\.(npz)')
"""
file_list = load_file_list(path=path, regx=regx)
for f in file_list:
W = load_npz(path, f)[0]
logging.info("%s --> %s" % (f, f.split('.')[0] + '.pdf'))
visualize.draw_weights(W, second=10, saveable=True, name=f.split('.')[0], fig_idx=2012) | python | def npz_to_W_pdf(path=None, regx='w1pre_[0-9]+\.(npz)'):
r"""Convert the first weight matrix of `.npz` file to `.pdf` by using `tl.visualize.W()`.
Parameters
----------
path : str
A folder path to `npz` files.
regx : str
Regx for the file name.
Examples
---------
Convert the first weight matrix of w1_pre...npz file to w1_pre...pdf.
>>> tl.files.npz_to_W_pdf(path='/Users/.../npz_file/', regx='w1pre_[0-9]+\.(npz)')
"""
file_list = load_file_list(path=path, regx=regx)
for f in file_list:
W = load_npz(path, f)[0]
logging.info("%s --> %s" % (f, f.split('.')[0] + '.pdf'))
visualize.draw_weights(W, second=10, saveable=True, name=f.split('.')[0], fig_idx=2012) | [
"def",
"npz_to_W_pdf",
"(",
"path",
"=",
"None",
",",
"regx",
"=",
"'w1pre_[0-9]+\\.(npz)'",
")",
":",
"file_list",
"=",
"load_file_list",
"(",
"path",
"=",
"path",
",",
"regx",
"=",
"regx",
")",
"for",
"f",
"in",
"file_list",
":",
"W",
"=",
"load_npz",
"(",
"path",
",",
"f",
")",
"[",
"0",
"]",
"logging",
".",
"info",
"(",
"\"%s --> %s\"",
"%",
"(",
"f",
",",
"f",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"'.pdf'",
")",
")",
"visualize",
".",
"draw_weights",
"(",
"W",
",",
"second",
"=",
"10",
",",
"saveable",
"=",
"True",
",",
"name",
"=",
"f",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
",",
"fig_idx",
"=",
"2012",
")"
] | r"""Convert the first weight matrix of `.npz` file to `.pdf` by using `tl.visualize.W()`.
Parameters
----------
path : str
A folder path to `npz` files.
regx : str
Regx for the file name.
Examples
---------
Convert the first weight matrix of w1_pre...npz file to w1_pre...pdf.
>>> tl.files.npz_to_W_pdf(path='/Users/.../npz_file/', regx='w1pre_[0-9]+\.(npz)') | [
"r",
"Convert",
"the",
"first",
"weight",
"matrix",
"of",
".",
"npz",
"file",
"to",
".",
"pdf",
"by",
"using",
"tl",
".",
"visualize",
".",
"W",
"()",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2335-L2356 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | threading_data | def threading_data(data=None, fn=None, thread_count=None, **kwargs):
"""Process a batch of data by given function by threading.
Usually be used for data augmentation.
Parameters
-----------
data : numpy.array or others
The data to be processed.
thread_count : int
The number of threads to use.
fn : function
The function for data processing.
more args : the args for `fn`
Ssee Examples below.
Examples
--------
Process images.
>>> images, _, _, _ = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
>>> images = tl.prepro.threading_data(images[0:32], tl.prepro.zoom, zoom_range=[0.5, 1])
Customized image preprocessing function.
>>> def distort_img(x):
>>> x = tl.prepro.flip_axis(x, axis=0, is_random=True)
>>> x = tl.prepro.flip_axis(x, axis=1, is_random=True)
>>> x = tl.prepro.crop(x, 100, 100, is_random=True)
>>> return x
>>> images = tl.prepro.threading_data(images, distort_img)
Process images and masks together (Usually be used for image segmentation).
>>> X, Y --> [batch_size, row, col, 1]
>>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], tl.prepro.zoom_multi, zoom_range=[0.5, 1], is_random=True)
data --> [batch_size, 2, row, col, 1]
>>> X_, Y_ = data.transpose((1,0,2,3,4))
X_, Y_ --> [batch_size, row, col, 1]
>>> tl.vis.save_image(X_, 'images.png')
>>> tl.vis.save_image(Y_, 'masks.png')
Process images and masks together by using ``thread_count``.
>>> X, Y --> [batch_size, row, col, 1]
>>> data = tl.prepro.threading_data(X, tl.prepro.zoom_multi, 8, zoom_range=[0.5, 1], is_random=True)
data --> [batch_size, 2, row, col, 1]
>>> X_, Y_ = data.transpose((1,0,2,3,4))
X_, Y_ --> [batch_size, row, col, 1]
>>> tl.vis.save_image(X_, 'after.png')
>>> tl.vis.save_image(Y_, 'before.png')
Customized function for processing images and masks together.
>>> def distort_img(data):
>>> x, y = data
>>> x, y = tl.prepro.flip_axis_multi([x, y], axis=0, is_random=True)
>>> x, y = tl.prepro.flip_axis_multi([x, y], axis=1, is_random=True)
>>> x, y = tl.prepro.crop_multi([x, y], 100, 100, is_random=True)
>>> return x, y
>>> X, Y --> [batch_size, row, col, channel]
>>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], distort_img)
>>> X_, Y_ = data.transpose((1,0,2,3,4))
Returns
-------
list or numpyarray
The processed results.
References
----------
- `python queue <https://pymotw.com/2/Queue/index.html#module-Queue>`__
- `run with limited queue <http://effbot.org/librarybook/queue.htm>`__
"""
def apply_fn(results, i, data, kwargs):
results[i] = fn(data, **kwargs)
if thread_count is None:
results = [None] * len(data)
threads = []
# for i in range(len(data)):
# t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, data[i], kwargs))
for i, d in enumerate(data):
t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, d, kwargs))
t.start()
threads.append(t)
else:
divs = np.linspace(0, len(data), thread_count + 1)
divs = np.round(divs).astype(int)
results = [None] * thread_count
threads = []
for i in range(thread_count):
t = threading.Thread(
name='threading_and_return', target=apply_fn, args=(results, i, data[divs[i]:divs[i + 1]], kwargs)
)
t.start()
threads.append(t)
for t in threads:
t.join()
if thread_count is None:
try:
return np.asarray(results)
except Exception:
return results
else:
return np.concatenate(results) | python | def threading_data(data=None, fn=None, thread_count=None, **kwargs):
"""Process a batch of data by given function by threading.
Usually be used for data augmentation.
Parameters
-----------
data : numpy.array or others
The data to be processed.
thread_count : int
The number of threads to use.
fn : function
The function for data processing.
more args : the args for `fn`
Ssee Examples below.
Examples
--------
Process images.
>>> images, _, _, _ = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
>>> images = tl.prepro.threading_data(images[0:32], tl.prepro.zoom, zoom_range=[0.5, 1])
Customized image preprocessing function.
>>> def distort_img(x):
>>> x = tl.prepro.flip_axis(x, axis=0, is_random=True)
>>> x = tl.prepro.flip_axis(x, axis=1, is_random=True)
>>> x = tl.prepro.crop(x, 100, 100, is_random=True)
>>> return x
>>> images = tl.prepro.threading_data(images, distort_img)
Process images and masks together (Usually be used for image segmentation).
>>> X, Y --> [batch_size, row, col, 1]
>>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], tl.prepro.zoom_multi, zoom_range=[0.5, 1], is_random=True)
data --> [batch_size, 2, row, col, 1]
>>> X_, Y_ = data.transpose((1,0,2,3,4))
X_, Y_ --> [batch_size, row, col, 1]
>>> tl.vis.save_image(X_, 'images.png')
>>> tl.vis.save_image(Y_, 'masks.png')
Process images and masks together by using ``thread_count``.
>>> X, Y --> [batch_size, row, col, 1]
>>> data = tl.prepro.threading_data(X, tl.prepro.zoom_multi, 8, zoom_range=[0.5, 1], is_random=True)
data --> [batch_size, 2, row, col, 1]
>>> X_, Y_ = data.transpose((1,0,2,3,4))
X_, Y_ --> [batch_size, row, col, 1]
>>> tl.vis.save_image(X_, 'after.png')
>>> tl.vis.save_image(Y_, 'before.png')
Customized function for processing images and masks together.
>>> def distort_img(data):
>>> x, y = data
>>> x, y = tl.prepro.flip_axis_multi([x, y], axis=0, is_random=True)
>>> x, y = tl.prepro.flip_axis_multi([x, y], axis=1, is_random=True)
>>> x, y = tl.prepro.crop_multi([x, y], 100, 100, is_random=True)
>>> return x, y
>>> X, Y --> [batch_size, row, col, channel]
>>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], distort_img)
>>> X_, Y_ = data.transpose((1,0,2,3,4))
Returns
-------
list or numpyarray
The processed results.
References
----------
- `python queue <https://pymotw.com/2/Queue/index.html#module-Queue>`__
- `run with limited queue <http://effbot.org/librarybook/queue.htm>`__
"""
def apply_fn(results, i, data, kwargs):
results[i] = fn(data, **kwargs)
if thread_count is None:
results = [None] * len(data)
threads = []
# for i in range(len(data)):
# t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, data[i], kwargs))
for i, d in enumerate(data):
t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, d, kwargs))
t.start()
threads.append(t)
else:
divs = np.linspace(0, len(data), thread_count + 1)
divs = np.round(divs).astype(int)
results = [None] * thread_count
threads = []
for i in range(thread_count):
t = threading.Thread(
name='threading_and_return', target=apply_fn, args=(results, i, data[divs[i]:divs[i + 1]], kwargs)
)
t.start()
threads.append(t)
for t in threads:
t.join()
if thread_count is None:
try:
return np.asarray(results)
except Exception:
return results
else:
return np.concatenate(results) | [
"def",
"threading_data",
"(",
"data",
"=",
"None",
",",
"fn",
"=",
"None",
",",
"thread_count",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"apply_fn",
"(",
"results",
",",
"i",
",",
"data",
",",
"kwargs",
")",
":",
"results",
"[",
"i",
"]",
"=",
"fn",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
"if",
"thread_count",
"is",
"None",
":",
"results",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"data",
")",
"threads",
"=",
"[",
"]",
"# for i in range(len(data)):",
"# t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, data[i], kwargs))",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"data",
")",
":",
"t",
"=",
"threading",
".",
"Thread",
"(",
"name",
"=",
"'threading_and_return'",
",",
"target",
"=",
"apply_fn",
",",
"args",
"=",
"(",
"results",
",",
"i",
",",
"d",
",",
"kwargs",
")",
")",
"t",
".",
"start",
"(",
")",
"threads",
".",
"append",
"(",
"t",
")",
"else",
":",
"divs",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"thread_count",
"+",
"1",
")",
"divs",
"=",
"np",
".",
"round",
"(",
"divs",
")",
".",
"astype",
"(",
"int",
")",
"results",
"=",
"[",
"None",
"]",
"*",
"thread_count",
"threads",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"thread_count",
")",
":",
"t",
"=",
"threading",
".",
"Thread",
"(",
"name",
"=",
"'threading_and_return'",
",",
"target",
"=",
"apply_fn",
",",
"args",
"=",
"(",
"results",
",",
"i",
",",
"data",
"[",
"divs",
"[",
"i",
"]",
":",
"divs",
"[",
"i",
"+",
"1",
"]",
"]",
",",
"kwargs",
")",
")",
"t",
".",
"start",
"(",
")",
"threads",
".",
"append",
"(",
"t",
")",
"for",
"t",
"in",
"threads",
":",
"t",
".",
"join",
"(",
")",
"if",
"thread_count",
"is",
"None",
":",
"try",
":",
"return",
"np",
".",
"asarray",
"(",
"results",
")",
"except",
"Exception",
":",
"return",
"results",
"else",
":",
"return",
"np",
".",
"concatenate",
"(",
"results",
")"
] | Process a batch of data by given function by threading.
Usually be used for data augmentation.
Parameters
-----------
data : numpy.array or others
The data to be processed.
thread_count : int
The number of threads to use.
fn : function
The function for data processing.
more args : the args for `fn`
Ssee Examples below.
Examples
--------
Process images.
>>> images, _, _, _ = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3))
>>> images = tl.prepro.threading_data(images[0:32], tl.prepro.zoom, zoom_range=[0.5, 1])
Customized image preprocessing function.
>>> def distort_img(x):
>>> x = tl.prepro.flip_axis(x, axis=0, is_random=True)
>>> x = tl.prepro.flip_axis(x, axis=1, is_random=True)
>>> x = tl.prepro.crop(x, 100, 100, is_random=True)
>>> return x
>>> images = tl.prepro.threading_data(images, distort_img)
Process images and masks together (Usually be used for image segmentation).
>>> X, Y --> [batch_size, row, col, 1]
>>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], tl.prepro.zoom_multi, zoom_range=[0.5, 1], is_random=True)
data --> [batch_size, 2, row, col, 1]
>>> X_, Y_ = data.transpose((1,0,2,3,4))
X_, Y_ --> [batch_size, row, col, 1]
>>> tl.vis.save_image(X_, 'images.png')
>>> tl.vis.save_image(Y_, 'masks.png')
Process images and masks together by using ``thread_count``.
>>> X, Y --> [batch_size, row, col, 1]
>>> data = tl.prepro.threading_data(X, tl.prepro.zoom_multi, 8, zoom_range=[0.5, 1], is_random=True)
data --> [batch_size, 2, row, col, 1]
>>> X_, Y_ = data.transpose((1,0,2,3,4))
X_, Y_ --> [batch_size, row, col, 1]
>>> tl.vis.save_image(X_, 'after.png')
>>> tl.vis.save_image(Y_, 'before.png')
Customized function for processing images and masks together.
>>> def distort_img(data):
>>> x, y = data
>>> x, y = tl.prepro.flip_axis_multi([x, y], axis=0, is_random=True)
>>> x, y = tl.prepro.flip_axis_multi([x, y], axis=1, is_random=True)
>>> x, y = tl.prepro.crop_multi([x, y], 100, 100, is_random=True)
>>> return x, y
>>> X, Y --> [batch_size, row, col, channel]
>>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], distort_img)
>>> X_, Y_ = data.transpose((1,0,2,3,4))
Returns
-------
list or numpyarray
The processed results.
References
----------
- `python queue <https://pymotw.com/2/Queue/index.html#module-Queue>`__
- `run with limited queue <http://effbot.org/librarybook/queue.htm>`__ | [
"Process",
"a",
"batch",
"of",
"data",
"by",
"given",
"function",
"by",
"threading",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L124-L234 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_rotation_matrix | def affine_rotation_matrix(angle=(-20, 20)):
"""Create an affine transform matrix for image rotation.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
angle : int/float or tuple of two int/float
Degree to rotate, usually -180 ~ 180.
- int/float, a fixed angle.
- tuple of 2 floats/ints, randomly sample a value as the angle between these 2 values.
Returns
-------
numpy.array
An affine transform matrix.
"""
if isinstance(angle, tuple):
theta = np.pi / 180 * np.random.uniform(angle[0], angle[1])
else:
theta = np.pi / 180 * angle
rotation_matrix = np.array([[np.cos(theta), np.sin(theta), 0], \
[-np.sin(theta), np.cos(theta), 0], \
[0, 0, 1]])
return rotation_matrix | python | def affine_rotation_matrix(angle=(-20, 20)):
"""Create an affine transform matrix for image rotation.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
angle : int/float or tuple of two int/float
Degree to rotate, usually -180 ~ 180.
- int/float, a fixed angle.
- tuple of 2 floats/ints, randomly sample a value as the angle between these 2 values.
Returns
-------
numpy.array
An affine transform matrix.
"""
if isinstance(angle, tuple):
theta = np.pi / 180 * np.random.uniform(angle[0], angle[1])
else:
theta = np.pi / 180 * angle
rotation_matrix = np.array([[np.cos(theta), np.sin(theta), 0], \
[-np.sin(theta), np.cos(theta), 0], \
[0, 0, 1]])
return rotation_matrix | [
"def",
"affine_rotation_matrix",
"(",
"angle",
"=",
"(",
"-",
"20",
",",
"20",
")",
")",
":",
"if",
"isinstance",
"(",
"angle",
",",
"tuple",
")",
":",
"theta",
"=",
"np",
".",
"pi",
"/",
"180",
"*",
"np",
".",
"random",
".",
"uniform",
"(",
"angle",
"[",
"0",
"]",
",",
"angle",
"[",
"1",
"]",
")",
"else",
":",
"theta",
"=",
"np",
".",
"pi",
"/",
"180",
"*",
"angle",
"rotation_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"return",
"rotation_matrix"
] | Create an affine transform matrix for image rotation.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
angle : int/float or tuple of two int/float
Degree to rotate, usually -180 ~ 180.
- int/float, a fixed angle.
- tuple of 2 floats/ints, randomly sample a value as the angle between these 2 values.
Returns
-------
numpy.array
An affine transform matrix. | [
"Create",
"an",
"affine",
"transform",
"matrix",
"for",
"image",
"rotation",
".",
"NOTE",
":",
"In",
"OpenCV",
"x",
"is",
"width",
"and",
"y",
"is",
"height",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L237-L261 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_horizontal_flip_matrix | def affine_horizontal_flip_matrix(prob=0.5):
"""Create an affine transformation matrix for image horizontal flipping.
NOTE: In OpenCV, x is width and y is height.
Parameters
----------
prob : float
Probability to flip the image. 1.0 means always flip.
Returns
-------
numpy.array
An affine transform matrix.
"""
factor = np.random.uniform(0, 1)
if prob >= factor:
filp_matrix = np.array([[ -1. , 0., 0. ], \
[ 0., 1., 0. ], \
[ 0., 0., 1. ]])
return filp_matrix
else:
filp_matrix = np.array([[ 1. , 0., 0. ], \
[ 0., 1., 0. ], \
[ 0., 0., 1. ]])
return filp_matrix | python | def affine_horizontal_flip_matrix(prob=0.5):
"""Create an affine transformation matrix for image horizontal flipping.
NOTE: In OpenCV, x is width and y is height.
Parameters
----------
prob : float
Probability to flip the image. 1.0 means always flip.
Returns
-------
numpy.array
An affine transform matrix.
"""
factor = np.random.uniform(0, 1)
if prob >= factor:
filp_matrix = np.array([[ -1. , 0., 0. ], \
[ 0., 1., 0. ], \
[ 0., 0., 1. ]])
return filp_matrix
else:
filp_matrix = np.array([[ 1. , 0., 0. ], \
[ 0., 1., 0. ], \
[ 0., 0., 1. ]])
return filp_matrix | [
"def",
"affine_horizontal_flip_matrix",
"(",
"prob",
"=",
"0.5",
")",
":",
"factor",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
")",
"if",
"prob",
">=",
"factor",
":",
"filp_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"-",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"1.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"0.",
",",
"1.",
"]",
"]",
")",
"return",
"filp_matrix",
"else",
":",
"filp_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"1.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"0.",
",",
"1.",
"]",
"]",
")",
"return",
"filp_matrix"
] | Create an affine transformation matrix for image horizontal flipping.
NOTE: In OpenCV, x is width and y is height.
Parameters
----------
prob : float
Probability to flip the image. 1.0 means always flip.
Returns
-------
numpy.array
An affine transform matrix. | [
"Create",
"an",
"affine",
"transformation",
"matrix",
"for",
"image",
"horizontal",
"flipping",
".",
"NOTE",
":",
"In",
"OpenCV",
"x",
"is",
"width",
"and",
"y",
"is",
"height",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L264-L289 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_vertical_flip_matrix | def affine_vertical_flip_matrix(prob=0.5):
"""Create an affine transformation for image vertical flipping.
NOTE: In OpenCV, x is width and y is height.
Parameters
----------
prob : float
Probability to flip the image. 1.0 means always flip.
Returns
-------
numpy.array
An affine transform matrix.
"""
factor = np.random.uniform(0, 1)
if prob >= factor:
filp_matrix = np.array([[ 1. , 0., 0. ], \
[ 0., -1., 0. ], \
[ 0., 0., 1. ]])
return filp_matrix
else:
filp_matrix = np.array([[ 1. , 0., 0. ], \
[ 0., 1., 0. ], \
[ 0., 0., 1. ]])
return filp_matrix | python | def affine_vertical_flip_matrix(prob=0.5):
"""Create an affine transformation for image vertical flipping.
NOTE: In OpenCV, x is width and y is height.
Parameters
----------
prob : float
Probability to flip the image. 1.0 means always flip.
Returns
-------
numpy.array
An affine transform matrix.
"""
factor = np.random.uniform(0, 1)
if prob >= factor:
filp_matrix = np.array([[ 1. , 0., 0. ], \
[ 0., -1., 0. ], \
[ 0., 0., 1. ]])
return filp_matrix
else:
filp_matrix = np.array([[ 1. , 0., 0. ], \
[ 0., 1., 0. ], \
[ 0., 0., 1. ]])
return filp_matrix | [
"def",
"affine_vertical_flip_matrix",
"(",
"prob",
"=",
"0.5",
")",
":",
"factor",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
")",
"if",
"prob",
">=",
"factor",
":",
"filp_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"-",
"1.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"0.",
",",
"1.",
"]",
"]",
")",
"return",
"filp_matrix",
"else",
":",
"filp_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"1.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"0.",
",",
"1.",
"]",
"]",
")",
"return",
"filp_matrix"
] | Create an affine transformation for image vertical flipping.
NOTE: In OpenCV, x is width and y is height.
Parameters
----------
prob : float
Probability to flip the image. 1.0 means always flip.
Returns
-------
numpy.array
An affine transform matrix. | [
"Create",
"an",
"affine",
"transformation",
"for",
"image",
"vertical",
"flipping",
".",
"NOTE",
":",
"In",
"OpenCV",
"x",
"is",
"width",
"and",
"y",
"is",
"height",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L292-L317 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_shift_matrix | def affine_shift_matrix(wrg=(-0.1, 0.1), hrg=(-0.1, 0.1), w=200, h=200):
"""Create an affine transform matrix for image shifting.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
wrg : float or tuple of floats
Range to shift on width axis, -1 ~ 1.
- float, a fixed distance.
- tuple of 2 floats, randomly sample a value as the distance between these 2 values.
hrg : float or tuple of floats
Range to shift on height axis, -1 ~ 1.
- float, a fixed distance.
- tuple of 2 floats, randomly sample a value as the distance between these 2 values.
w, h : int
The width and height of the image.
Returns
-------
numpy.array
An affine transform matrix.
"""
if isinstance(wrg, tuple):
tx = np.random.uniform(wrg[0], wrg[1]) * w
else:
tx = wrg * w
if isinstance(hrg, tuple):
ty = np.random.uniform(hrg[0], hrg[1]) * h
else:
ty = hrg * h
shift_matrix = np.array([[1, 0, tx], \
[0, 1, ty], \
[0, 0, 1]])
return shift_matrix | python | def affine_shift_matrix(wrg=(-0.1, 0.1), hrg=(-0.1, 0.1), w=200, h=200):
"""Create an affine transform matrix for image shifting.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
wrg : float or tuple of floats
Range to shift on width axis, -1 ~ 1.
- float, a fixed distance.
- tuple of 2 floats, randomly sample a value as the distance between these 2 values.
hrg : float or tuple of floats
Range to shift on height axis, -1 ~ 1.
- float, a fixed distance.
- tuple of 2 floats, randomly sample a value as the distance between these 2 values.
w, h : int
The width and height of the image.
Returns
-------
numpy.array
An affine transform matrix.
"""
if isinstance(wrg, tuple):
tx = np.random.uniform(wrg[0], wrg[1]) * w
else:
tx = wrg * w
if isinstance(hrg, tuple):
ty = np.random.uniform(hrg[0], hrg[1]) * h
else:
ty = hrg * h
shift_matrix = np.array([[1, 0, tx], \
[0, 1, ty], \
[0, 0, 1]])
return shift_matrix | [
"def",
"affine_shift_matrix",
"(",
"wrg",
"=",
"(",
"-",
"0.1",
",",
"0.1",
")",
",",
"hrg",
"=",
"(",
"-",
"0.1",
",",
"0.1",
")",
",",
"w",
"=",
"200",
",",
"h",
"=",
"200",
")",
":",
"if",
"isinstance",
"(",
"wrg",
",",
"tuple",
")",
":",
"tx",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"wrg",
"[",
"0",
"]",
",",
"wrg",
"[",
"1",
"]",
")",
"*",
"w",
"else",
":",
"tx",
"=",
"wrg",
"*",
"w",
"if",
"isinstance",
"(",
"hrg",
",",
"tuple",
")",
":",
"ty",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"hrg",
"[",
"0",
"]",
",",
"hrg",
"[",
"1",
"]",
")",
"*",
"h",
"else",
":",
"ty",
"=",
"hrg",
"*",
"h",
"shift_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"tx",
"]",
",",
"[",
"0",
",",
"1",
",",
"ty",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"return",
"shift_matrix"
] | Create an affine transform matrix for image shifting.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
wrg : float or tuple of floats
Range to shift on width axis, -1 ~ 1.
- float, a fixed distance.
- tuple of 2 floats, randomly sample a value as the distance between these 2 values.
hrg : float or tuple of floats
Range to shift on height axis, -1 ~ 1.
- float, a fixed distance.
- tuple of 2 floats, randomly sample a value as the distance between these 2 values.
w, h : int
The width and height of the image.
Returns
-------
numpy.array
An affine transform matrix. | [
"Create",
"an",
"affine",
"transform",
"matrix",
"for",
"image",
"shifting",
".",
"NOTE",
":",
"In",
"OpenCV",
"x",
"is",
"width",
"and",
"y",
"is",
"height",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L320-L354 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_shear_matrix | def affine_shear_matrix(x_shear=(-0.1, 0.1), y_shear=(-0.1, 0.1)):
"""Create affine transform matrix for image shearing.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
shear : tuple of two floats
Percentage of shears for width and height directions.
Returns
-------
numpy.array
An affine transform matrix.
"""
# if len(shear) != 2:
# raise AssertionError(
# "shear should be tuple of 2 floats, or you want to use tl.prepro.shear rather than tl.prepro.shear2 ?"
# )
# if isinstance(shear, tuple):
# shear = list(shear)
# if is_random:
# shear[0] = np.random.uniform(-shear[0], shear[0])
# shear[1] = np.random.uniform(-shear[1], shear[1])
if isinstance(x_shear, tuple):
x_shear = np.random.uniform(x_shear[0], x_shear[1])
if isinstance(y_shear, tuple):
y_shear = np.random.uniform(y_shear[0], y_shear[1])
shear_matrix = np.array([[1, x_shear, 0], \
[y_shear, 1, 0], \
[0, 0, 1]])
return shear_matrix | python | def affine_shear_matrix(x_shear=(-0.1, 0.1), y_shear=(-0.1, 0.1)):
"""Create affine transform matrix for image shearing.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
shear : tuple of two floats
Percentage of shears for width and height directions.
Returns
-------
numpy.array
An affine transform matrix.
"""
# if len(shear) != 2:
# raise AssertionError(
# "shear should be tuple of 2 floats, or you want to use tl.prepro.shear rather than tl.prepro.shear2 ?"
# )
# if isinstance(shear, tuple):
# shear = list(shear)
# if is_random:
# shear[0] = np.random.uniform(-shear[0], shear[0])
# shear[1] = np.random.uniform(-shear[1], shear[1])
if isinstance(x_shear, tuple):
x_shear = np.random.uniform(x_shear[0], x_shear[1])
if isinstance(y_shear, tuple):
y_shear = np.random.uniform(y_shear[0], y_shear[1])
shear_matrix = np.array([[1, x_shear, 0], \
[y_shear, 1, 0], \
[0, 0, 1]])
return shear_matrix | [
"def",
"affine_shear_matrix",
"(",
"x_shear",
"=",
"(",
"-",
"0.1",
",",
"0.1",
")",
",",
"y_shear",
"=",
"(",
"-",
"0.1",
",",
"0.1",
")",
")",
":",
"# if len(shear) != 2:",
"# raise AssertionError(",
"# \"shear should be tuple of 2 floats, or you want to use tl.prepro.shear rather than tl.prepro.shear2 ?\"",
"# )",
"# if isinstance(shear, tuple):",
"# shear = list(shear)",
"# if is_random:",
"# shear[0] = np.random.uniform(-shear[0], shear[0])",
"# shear[1] = np.random.uniform(-shear[1], shear[1])",
"if",
"isinstance",
"(",
"x_shear",
",",
"tuple",
")",
":",
"x_shear",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"x_shear",
"[",
"0",
"]",
",",
"x_shear",
"[",
"1",
"]",
")",
"if",
"isinstance",
"(",
"y_shear",
",",
"tuple",
")",
":",
"y_shear",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"y_shear",
"[",
"0",
"]",
",",
"y_shear",
"[",
"1",
"]",
")",
"shear_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"x_shear",
",",
"0",
"]",
",",
"[",
"y_shear",
",",
"1",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"return",
"shear_matrix"
] | Create affine transform matrix for image shearing.
NOTE: In OpenCV, x is width and y is height.
Parameters
-----------
shear : tuple of two floats
Percentage of shears for width and height directions.
Returns
-------
numpy.array
An affine transform matrix. | [
"Create",
"affine",
"transform",
"matrix",
"for",
"image",
"shearing",
".",
"NOTE",
":",
"In",
"OpenCV",
"x",
"is",
"width",
"and",
"y",
"is",
"height",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L357-L389 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_zoom_matrix | def affine_zoom_matrix(zoom_range=(0.8, 1.1)):
"""Create an affine transform matrix for zooming/scaling an image's height and width.
OpenCV format, x is width.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
zoom_range : float or tuple of 2 floats
The zooming/scaling ratio, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between these 2 values.
Returns
-------
numpy.array
An affine transform matrix.
"""
if isinstance(zoom_range, (float, int)):
scale = zoom_range
elif isinstance(zoom_range, tuple):
scale = np.random.uniform(zoom_range[0], zoom_range[1])
else:
raise Exception("zoom_range: float or tuple of 2 floats")
zoom_matrix = np.array([[scale, 0, 0], \
[0, scale, 0], \
[0, 0, 1]])
return zoom_matrix | python | def affine_zoom_matrix(zoom_range=(0.8, 1.1)):
"""Create an affine transform matrix for zooming/scaling an image's height and width.
OpenCV format, x is width.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
zoom_range : float or tuple of 2 floats
The zooming/scaling ratio, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between these 2 values.
Returns
-------
numpy.array
An affine transform matrix.
"""
if isinstance(zoom_range, (float, int)):
scale = zoom_range
elif isinstance(zoom_range, tuple):
scale = np.random.uniform(zoom_range[0], zoom_range[1])
else:
raise Exception("zoom_range: float or tuple of 2 floats")
zoom_matrix = np.array([[scale, 0, 0], \
[0, scale, 0], \
[0, 0, 1]])
return zoom_matrix | [
"def",
"affine_zoom_matrix",
"(",
"zoom_range",
"=",
"(",
"0.8",
",",
"1.1",
")",
")",
":",
"if",
"isinstance",
"(",
"zoom_range",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"scale",
"=",
"zoom_range",
"elif",
"isinstance",
"(",
"zoom_range",
",",
"tuple",
")",
":",
"scale",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"zoom_range",
"[",
"0",
"]",
",",
"zoom_range",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"zoom_range: float or tuple of 2 floats\"",
")",
"zoom_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"scale",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"scale",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"return",
"zoom_matrix"
] | Create an affine transform matrix for zooming/scaling an image's height and width.
OpenCV format, x is width.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
zoom_range : float or tuple of 2 floats
The zooming/scaling ratio, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between these 2 values.
Returns
-------
numpy.array
An affine transform matrix. | [
"Create",
"an",
"affine",
"transform",
"matrix",
"for",
"zooming",
"/",
"scaling",
"an",
"image",
"s",
"height",
"and",
"width",
".",
"OpenCV",
"format",
"x",
"is",
"width",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L392-L422 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_respective_zoom_matrix | def affine_respective_zoom_matrix(w_range=0.8, h_range=1.1):
"""Get affine transform matrix for zooming/scaling that height and width are changed independently.
OpenCV format, x is width.
Parameters
-----------
w_range : float or tuple of 2 floats
The zooming/scaling ratio of width, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
h_range : float or tuple of 2 floats
The zooming/scaling ratio of height, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
Returns
-------
numpy.array
An affine transform matrix.
"""
if isinstance(h_range, (float, int)):
zy = h_range
elif isinstance(h_range, tuple):
zy = np.random.uniform(h_range[0], h_range[1])
else:
raise Exception("h_range: float or tuple of 2 floats")
if isinstance(w_range, (float, int)):
zx = w_range
elif isinstance(w_range, tuple):
zx = np.random.uniform(w_range[0], w_range[1])
else:
raise Exception("w_range: float or tuple of 2 floats")
zoom_matrix = np.array([[zx, 0, 0], \
[0, zy, 0], \
[0, 0, 1]])
return zoom_matrix | python | def affine_respective_zoom_matrix(w_range=0.8, h_range=1.1):
"""Get affine transform matrix for zooming/scaling that height and width are changed independently.
OpenCV format, x is width.
Parameters
-----------
w_range : float or tuple of 2 floats
The zooming/scaling ratio of width, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
h_range : float or tuple of 2 floats
The zooming/scaling ratio of height, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
Returns
-------
numpy.array
An affine transform matrix.
"""
if isinstance(h_range, (float, int)):
zy = h_range
elif isinstance(h_range, tuple):
zy = np.random.uniform(h_range[0], h_range[1])
else:
raise Exception("h_range: float or tuple of 2 floats")
if isinstance(w_range, (float, int)):
zx = w_range
elif isinstance(w_range, tuple):
zx = np.random.uniform(w_range[0], w_range[1])
else:
raise Exception("w_range: float or tuple of 2 floats")
zoom_matrix = np.array([[zx, 0, 0], \
[0, zy, 0], \
[0, 0, 1]])
return zoom_matrix | [
"def",
"affine_respective_zoom_matrix",
"(",
"w_range",
"=",
"0.8",
",",
"h_range",
"=",
"1.1",
")",
":",
"if",
"isinstance",
"(",
"h_range",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"zy",
"=",
"h_range",
"elif",
"isinstance",
"(",
"h_range",
",",
"tuple",
")",
":",
"zy",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"h_range",
"[",
"0",
"]",
",",
"h_range",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"h_range: float or tuple of 2 floats\"",
")",
"if",
"isinstance",
"(",
"w_range",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"zx",
"=",
"w_range",
"elif",
"isinstance",
"(",
"w_range",
",",
"tuple",
")",
":",
"zx",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"w_range",
"[",
"0",
"]",
",",
"w_range",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"w_range: float or tuple of 2 floats\"",
")",
"zoom_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"zx",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"zy",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"return",
"zoom_matrix"
] | Get affine transform matrix for zooming/scaling that height and width are changed independently.
OpenCV format, x is width.
Parameters
-----------
w_range : float or tuple of 2 floats
The zooming/scaling ratio of width, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
h_range : float or tuple of 2 floats
The zooming/scaling ratio of height, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
Returns
-------
numpy.array
An affine transform matrix. | [
"Get",
"affine",
"transform",
"matrix",
"for",
"zooming",
"/",
"scaling",
"that",
"height",
"and",
"width",
"are",
"changed",
"independently",
".",
"OpenCV",
"format",
"x",
"is",
"width",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L425-L464 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | transform_matrix_offset_center | def transform_matrix_offset_center(matrix, y, x):
"""Convert the matrix from Cartesian coordinates (the origin in the middle of image) to Image coordinates (the origin on the top-left of image).
Parameters
----------
matrix : numpy.array
Transform matrix.
x and y : 2 int
Size of image.
Returns
-------
numpy.array
The transform matrix.
Examples
--------
- See ``tl.prepro.rotation``, ``tl.prepro.shear``, ``tl.prepro.zoom``.
"""
o_x = (x - 1) / 2.0
o_y = (y - 1) / 2.0
offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])
reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]])
transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)
return transform_matrix | python | def transform_matrix_offset_center(matrix, y, x):
"""Convert the matrix from Cartesian coordinates (the origin in the middle of image) to Image coordinates (the origin on the top-left of image).
Parameters
----------
matrix : numpy.array
Transform matrix.
x and y : 2 int
Size of image.
Returns
-------
numpy.array
The transform matrix.
Examples
--------
- See ``tl.prepro.rotation``, ``tl.prepro.shear``, ``tl.prepro.zoom``.
"""
o_x = (x - 1) / 2.0
o_y = (y - 1) / 2.0
offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])
reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]])
transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)
return transform_matrix | [
"def",
"transform_matrix_offset_center",
"(",
"matrix",
",",
"y",
",",
"x",
")",
":",
"o_x",
"=",
"(",
"x",
"-",
"1",
")",
"/",
"2.0",
"o_y",
"=",
"(",
"y",
"-",
"1",
")",
"/",
"2.0",
"offset_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"o_x",
"]",
",",
"[",
"0",
",",
"1",
",",
"o_y",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"reset_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"-",
"o_x",
"]",
",",
"[",
"0",
",",
"1",
",",
"-",
"o_y",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"transform_matrix",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"offset_matrix",
",",
"matrix",
")",
",",
"reset_matrix",
")",
"return",
"transform_matrix"
] | Convert the matrix from Cartesian coordinates (the origin in the middle of image) to Image coordinates (the origin on the top-left of image).
Parameters
----------
matrix : numpy.array
Transform matrix.
x and y : 2 int
Size of image.
Returns
-------
numpy.array
The transform matrix.
Examples
--------
- See ``tl.prepro.rotation``, ``tl.prepro.shear``, ``tl.prepro.zoom``. | [
"Convert",
"the",
"matrix",
"from",
"Cartesian",
"coordinates",
"(",
"the",
"origin",
"in",
"the",
"middle",
"of",
"image",
")",
"to",
"Image",
"coordinates",
"(",
"the",
"origin",
"on",
"the",
"top",
"-",
"left",
"of",
"image",
")",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L468-L492 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_transform | def affine_transform(x, transform_matrix, channel_index=2, fill_mode='nearest', cval=0., order=1):
"""Return transformed images by given an affine matrix in Scipy format (x is height).
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
transform_matrix : numpy.array
Transform matrix (offset center), can be generated by ``transform_matrix_offset_center``
channel_index : int
Index of channel, default 2.
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0
order : int
The order of interpolation. The order has to be in the range 0-5:
- 0 Nearest-neighbor
- 1 Bi-linear (default)
- 2 Bi-quadratic
- 3 Bi-cubic
- 4 Bi-quartic
- 5 Bi-quintic
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
Examples
--------
>>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False)
>>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8)
>>> M_combined = M_shear.dot(M_zoom)
>>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, h, w)
>>> result = tl.prepro.affine_transform(image, transform_matrix)
"""
# transform_matrix = transform_matrix_offset_center()
# asdihasid
# asd
x = np.rollaxis(x, channel_index, 0)
final_affine_matrix = transform_matrix[:2, :2]
final_offset = transform_matrix[:2, 2]
channel_images = [
ndi.interpolation.
affine_transform(x_channel, final_affine_matrix, final_offset, order=order, mode=fill_mode, cval=cval)
for x_channel in x
]
x = np.stack(channel_images, axis=0)
x = np.rollaxis(x, 0, channel_index + 1)
return x | python | def affine_transform(x, transform_matrix, channel_index=2, fill_mode='nearest', cval=0., order=1):
"""Return transformed images by given an affine matrix in Scipy format (x is height).
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
transform_matrix : numpy.array
Transform matrix (offset center), can be generated by ``transform_matrix_offset_center``
channel_index : int
Index of channel, default 2.
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0
order : int
The order of interpolation. The order has to be in the range 0-5:
- 0 Nearest-neighbor
- 1 Bi-linear (default)
- 2 Bi-quadratic
- 3 Bi-cubic
- 4 Bi-quartic
- 5 Bi-quintic
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
Examples
--------
>>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False)
>>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8)
>>> M_combined = M_shear.dot(M_zoom)
>>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, h, w)
>>> result = tl.prepro.affine_transform(image, transform_matrix)
"""
# transform_matrix = transform_matrix_offset_center()
# asdihasid
# asd
x = np.rollaxis(x, channel_index, 0)
final_affine_matrix = transform_matrix[:2, :2]
final_offset = transform_matrix[:2, 2]
channel_images = [
ndi.interpolation.
affine_transform(x_channel, final_affine_matrix, final_offset, order=order, mode=fill_mode, cval=cval)
for x_channel in x
]
x = np.stack(channel_images, axis=0)
x = np.rollaxis(x, 0, channel_index + 1)
return x | [
"def",
"affine_transform",
"(",
"x",
",",
"transform_matrix",
",",
"channel_index",
"=",
"2",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
",",
"order",
"=",
"1",
")",
":",
"# transform_matrix = transform_matrix_offset_center()",
"# asdihasid",
"# asd",
"x",
"=",
"np",
".",
"rollaxis",
"(",
"x",
",",
"channel_index",
",",
"0",
")",
"final_affine_matrix",
"=",
"transform_matrix",
"[",
":",
"2",
",",
":",
"2",
"]",
"final_offset",
"=",
"transform_matrix",
"[",
":",
"2",
",",
"2",
"]",
"channel_images",
"=",
"[",
"ndi",
".",
"interpolation",
".",
"affine_transform",
"(",
"x_channel",
",",
"final_affine_matrix",
",",
"final_offset",
",",
"order",
"=",
"order",
",",
"mode",
"=",
"fill_mode",
",",
"cval",
"=",
"cval",
")",
"for",
"x_channel",
"in",
"x",
"]",
"x",
"=",
"np",
".",
"stack",
"(",
"channel_images",
",",
"axis",
"=",
"0",
")",
"x",
"=",
"np",
".",
"rollaxis",
"(",
"x",
",",
"0",
",",
"channel_index",
"+",
"1",
")",
"return",
"x"
] | Return transformed images by given an affine matrix in Scipy format (x is height).
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
transform_matrix : numpy.array
Transform matrix (offset center), can be generated by ``transform_matrix_offset_center``
channel_index : int
Index of channel, default 2.
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0
order : int
The order of interpolation. The order has to be in the range 0-5:
- 0 Nearest-neighbor
- 1 Bi-linear (default)
- 2 Bi-quadratic
- 3 Bi-cubic
- 4 Bi-quartic
- 5 Bi-quintic
- `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
Examples
--------
>>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False)
>>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8)
>>> M_combined = M_shear.dot(M_zoom)
>>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, h, w)
>>> result = tl.prepro.affine_transform(image, transform_matrix) | [
"Return",
"transformed",
"images",
"by",
"given",
"an",
"affine",
"matrix",
"in",
"Scipy",
"format",
"(",
"x",
"is",
"height",
")",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L495-L548 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_transform_cv2 | def affine_transform_cv2(x, transform_matrix, flags=None, border_mode='constant'):
"""Return transformed images by given an affine matrix in OpenCV format (x is width). (Powered by OpenCV2, faster than ``tl.prepro.affine_transform``)
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
transform_matrix : numpy.array
A transform matrix, OpenCV format.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Examples
--------
>>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False)
>>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8)
>>> M_combined = M_shear.dot(M_zoom)
>>> result = tl.prepro.affine_transform_cv2(image, M_combined)
"""
rows, cols = x.shape[0], x.shape[1]
if flags is None:
flags = cv2.INTER_AREA
if border_mode is 'constant':
border_mode = cv2.BORDER_CONSTANT
elif border_mode is 'replicate':
border_mode = cv2.BORDER_REPLICATE
else:
raise Exception("unsupport border_mode, check cv.BORDER_ for more details.")
return cv2.warpAffine(x, transform_matrix[0:2,:], \
(cols,rows), flags=flags, borderMode=border_mode) | python | def affine_transform_cv2(x, transform_matrix, flags=None, border_mode='constant'):
"""Return transformed images by given an affine matrix in OpenCV format (x is width). (Powered by OpenCV2, faster than ``tl.prepro.affine_transform``)
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
transform_matrix : numpy.array
A transform matrix, OpenCV format.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Examples
--------
>>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False)
>>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8)
>>> M_combined = M_shear.dot(M_zoom)
>>> result = tl.prepro.affine_transform_cv2(image, M_combined)
"""
rows, cols = x.shape[0], x.shape[1]
if flags is None:
flags = cv2.INTER_AREA
if border_mode is 'constant':
border_mode = cv2.BORDER_CONSTANT
elif border_mode is 'replicate':
border_mode = cv2.BORDER_REPLICATE
else:
raise Exception("unsupport border_mode, check cv.BORDER_ for more details.")
return cv2.warpAffine(x, transform_matrix[0:2,:], \
(cols,rows), flags=flags, borderMode=border_mode) | [
"def",
"affine_transform_cv2",
"(",
"x",
",",
"transform_matrix",
",",
"flags",
"=",
"None",
",",
"border_mode",
"=",
"'constant'",
")",
":",
"rows",
",",
"cols",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"x",
".",
"shape",
"[",
"1",
"]",
"if",
"flags",
"is",
"None",
":",
"flags",
"=",
"cv2",
".",
"INTER_AREA",
"if",
"border_mode",
"is",
"'constant'",
":",
"border_mode",
"=",
"cv2",
".",
"BORDER_CONSTANT",
"elif",
"border_mode",
"is",
"'replicate'",
":",
"border_mode",
"=",
"cv2",
".",
"BORDER_REPLICATE",
"else",
":",
"raise",
"Exception",
"(",
"\"unsupport border_mode, check cv.BORDER_ for more details.\"",
")",
"return",
"cv2",
".",
"warpAffine",
"(",
"x",
",",
"transform_matrix",
"[",
"0",
":",
"2",
",",
":",
"]",
",",
"(",
"cols",
",",
"rows",
")",
",",
"flags",
"=",
"flags",
",",
"borderMode",
"=",
"border_mode",
")"
] | Return transformed images by given an affine matrix in OpenCV format (x is width). (Powered by OpenCV2, faster than ``tl.prepro.affine_transform``)
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
transform_matrix : numpy.array
A transform matrix, OpenCV format.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Examples
--------
>>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False)
>>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8)
>>> M_combined = M_shear.dot(M_zoom)
>>> result = tl.prepro.affine_transform_cv2(image, M_combined) | [
"Return",
"transformed",
"images",
"by",
"given",
"an",
"affine",
"matrix",
"in",
"OpenCV",
"format",
"(",
"x",
"is",
"width",
")",
".",
"(",
"Powered",
"by",
"OpenCV2",
"faster",
"than",
"tl",
".",
"prepro",
".",
"affine_transform",
")"
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L554-L584 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | affine_transform_keypoints | def affine_transform_keypoints(coords_list, transform_matrix):
"""Transform keypoint coordinates according to a given affine transform matrix.
OpenCV format, x is width.
Note that, for pose estimation task, flipping requires maintaining the left and right body information.
We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``.
Parameters
-----------
coords_list : list of list of tuple/list
The coordinates
e.g., the keypoint coordinates of every person in an image.
transform_matrix : numpy.array
Transform matrix, OpenCV format.
Examples
---------
>>> # 1. get all affine transform matrices
>>> M_rotate = tl.prepro.affine_rotation_matrix(angle=20)
>>> M_flip = tl.prepro.affine_horizontal_flip_matrix(prob=1)
>>> # 2. combine all affine transform matrices to one matrix
>>> M_combined = dot(M_flip).dot(M_rotate)
>>> # 3. transfrom the matrix from Cartesian coordinate (the origin in the middle of image)
>>> # to Image coordinate (the origin on the top-left of image)
>>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, x=w, y=h)
>>> # 4. then we can transfrom the image once for all transformations
>>> result = tl.prepro.affine_transform_cv2(image, transform_matrix) # 76 times faster
>>> # 5. transform keypoint coordinates
>>> coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]]
>>> coords_result = tl.prepro.affine_transform_keypoints(coords, transform_matrix)
"""
coords_result_list = []
for coords in coords_list:
coords = np.asarray(coords)
coords = coords.transpose([1, 0])
coords = np.insert(coords, 2, 1, axis=0)
# print(coords)
# print(transform_matrix)
coords_result = np.matmul(transform_matrix, coords)
coords_result = coords_result[0:2, :].transpose([1, 0])
coords_result_list.append(coords_result)
return coords_result_list | python | def affine_transform_keypoints(coords_list, transform_matrix):
"""Transform keypoint coordinates according to a given affine transform matrix.
OpenCV format, x is width.
Note that, for pose estimation task, flipping requires maintaining the left and right body information.
We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``.
Parameters
-----------
coords_list : list of list of tuple/list
The coordinates
e.g., the keypoint coordinates of every person in an image.
transform_matrix : numpy.array
Transform matrix, OpenCV format.
Examples
---------
>>> # 1. get all affine transform matrices
>>> M_rotate = tl.prepro.affine_rotation_matrix(angle=20)
>>> M_flip = tl.prepro.affine_horizontal_flip_matrix(prob=1)
>>> # 2. combine all affine transform matrices to one matrix
>>> M_combined = dot(M_flip).dot(M_rotate)
>>> # 3. transfrom the matrix from Cartesian coordinate (the origin in the middle of image)
>>> # to Image coordinate (the origin on the top-left of image)
>>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, x=w, y=h)
>>> # 4. then we can transfrom the image once for all transformations
>>> result = tl.prepro.affine_transform_cv2(image, transform_matrix) # 76 times faster
>>> # 5. transform keypoint coordinates
>>> coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]]
>>> coords_result = tl.prepro.affine_transform_keypoints(coords, transform_matrix)
"""
coords_result_list = []
for coords in coords_list:
coords = np.asarray(coords)
coords = coords.transpose([1, 0])
coords = np.insert(coords, 2, 1, axis=0)
# print(coords)
# print(transform_matrix)
coords_result = np.matmul(transform_matrix, coords)
coords_result = coords_result[0:2, :].transpose([1, 0])
coords_result_list.append(coords_result)
return coords_result_list | [
"def",
"affine_transform_keypoints",
"(",
"coords_list",
",",
"transform_matrix",
")",
":",
"coords_result_list",
"=",
"[",
"]",
"for",
"coords",
"in",
"coords_list",
":",
"coords",
"=",
"np",
".",
"asarray",
"(",
"coords",
")",
"coords",
"=",
"coords",
".",
"transpose",
"(",
"[",
"1",
",",
"0",
"]",
")",
"coords",
"=",
"np",
".",
"insert",
"(",
"coords",
",",
"2",
",",
"1",
",",
"axis",
"=",
"0",
")",
"# print(coords)",
"# print(transform_matrix)",
"coords_result",
"=",
"np",
".",
"matmul",
"(",
"transform_matrix",
",",
"coords",
")",
"coords_result",
"=",
"coords_result",
"[",
"0",
":",
"2",
",",
":",
"]",
".",
"transpose",
"(",
"[",
"1",
",",
"0",
"]",
")",
"coords_result_list",
".",
"append",
"(",
"coords_result",
")",
"return",
"coords_result_list"
] | Transform keypoint coordinates according to a given affine transform matrix.
OpenCV format, x is width.
Note that, for pose estimation task, flipping requires maintaining the left and right body information.
We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``.
Parameters
-----------
coords_list : list of list of tuple/list
The coordinates
e.g., the keypoint coordinates of every person in an image.
transform_matrix : numpy.array
Transform matrix, OpenCV format.
Examples
---------
>>> # 1. get all affine transform matrices
>>> M_rotate = tl.prepro.affine_rotation_matrix(angle=20)
>>> M_flip = tl.prepro.affine_horizontal_flip_matrix(prob=1)
>>> # 2. combine all affine transform matrices to one matrix
>>> M_combined = dot(M_flip).dot(M_rotate)
>>> # 3. transfrom the matrix from Cartesian coordinate (the origin in the middle of image)
>>> # to Image coordinate (the origin on the top-left of image)
>>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, x=w, y=h)
>>> # 4. then we can transfrom the image once for all transformations
>>> result = tl.prepro.affine_transform_cv2(image, transform_matrix) # 76 times faster
>>> # 5. transform keypoint coordinates
>>> coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]]
>>> coords_result = tl.prepro.affine_transform_keypoints(coords, transform_matrix) | [
"Transform",
"keypoint",
"coordinates",
"according",
"to",
"a",
"given",
"affine",
"transform",
"matrix",
".",
"OpenCV",
"format",
"x",
"is",
"width",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L587-L628 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | projective_transform_by_points | def projective_transform_by_points(
x, src, dst, map_args=None, output_shape=None, order=1, mode='constant', cval=0.0, clip=True,
preserve_range=False
):
"""Projective transform by given coordinates, usually 4 coordinates.
see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
src : list or numpy
The original coordinates, usually 4 coordinates of (width, height).
dst : list or numpy
The coordinates after transformation, the number of coordinates is the same with src.
map_args : dictionary or None
Keyword arguments passed to inverse map.
output_shape : tuple of 2 int
Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified.
order : int
The order of interpolation. The order has to be in the range 0-5:
- 0 Nearest-neighbor
- 1 Bi-linear (default)
- 2 Bi-quadratic
- 3 Bi-cubic
- 4 Bi-quartic
- 5 Bi-quintic
mode : str
One of `constant` (default), `edge`, `symmetric`, `reflect` or `wrap`.
Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.
cval : float
Used in conjunction with mode `constant`, the value outside the image boundaries.
clip : boolean
Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
preserve_range : boolean
Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.
Returns
-------
numpy.array
A processed image.
Examples
--------
Assume X is an image from CIFAR-10, i.e. shape == (32, 32, 3)
>>> src = [[0,0],[0,32],[32,0],[32,32]] # [w, h]
>>> dst = [[10,10],[0,32],[32,0],[32,32]]
>>> x = tl.prepro.projective_transform_by_points(X, src, dst)
References
-----------
- `scikit-image : geometric transformations <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__
- `scikit-image : examples <http://scikit-image.org/docs/dev/auto_examples/index.html>`__
"""
if map_args is None:
map_args = {}
# if type(src) is list:
if isinstance(src, list): # convert to numpy
src = np.array(src)
# if type(dst) is list:
if isinstance(dst, list):
dst = np.array(dst)
if np.max(x) > 1: # convert to [0, 1]
x = x / 255
m = transform.ProjectiveTransform()
m.estimate(dst, src)
warped = transform.warp(
x, m, map_args=map_args, output_shape=output_shape, order=order, mode=mode, cval=cval, clip=clip,
preserve_range=preserve_range
)
return warped | python | def projective_transform_by_points(
x, src, dst, map_args=None, output_shape=None, order=1, mode='constant', cval=0.0, clip=True,
preserve_range=False
):
"""Projective transform by given coordinates, usually 4 coordinates.
see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
src : list or numpy
The original coordinates, usually 4 coordinates of (width, height).
dst : list or numpy
The coordinates after transformation, the number of coordinates is the same with src.
map_args : dictionary or None
Keyword arguments passed to inverse map.
output_shape : tuple of 2 int
Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified.
order : int
The order of interpolation. The order has to be in the range 0-5:
- 0 Nearest-neighbor
- 1 Bi-linear (default)
- 2 Bi-quadratic
- 3 Bi-cubic
- 4 Bi-quartic
- 5 Bi-quintic
mode : str
One of `constant` (default), `edge`, `symmetric`, `reflect` or `wrap`.
Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.
cval : float
Used in conjunction with mode `constant`, the value outside the image boundaries.
clip : boolean
Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
preserve_range : boolean
Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.
Returns
-------
numpy.array
A processed image.
Examples
--------
Assume X is an image from CIFAR-10, i.e. shape == (32, 32, 3)
>>> src = [[0,0],[0,32],[32,0],[32,32]] # [w, h]
>>> dst = [[10,10],[0,32],[32,0],[32,32]]
>>> x = tl.prepro.projective_transform_by_points(X, src, dst)
References
-----------
- `scikit-image : geometric transformations <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__
- `scikit-image : examples <http://scikit-image.org/docs/dev/auto_examples/index.html>`__
"""
if map_args is None:
map_args = {}
# if type(src) is list:
if isinstance(src, list): # convert to numpy
src = np.array(src)
# if type(dst) is list:
if isinstance(dst, list):
dst = np.array(dst)
if np.max(x) > 1: # convert to [0, 1]
x = x / 255
m = transform.ProjectiveTransform()
m.estimate(dst, src)
warped = transform.warp(
x, m, map_args=map_args, output_shape=output_shape, order=order, mode=mode, cval=cval, clip=clip,
preserve_range=preserve_range
)
return warped | [
"def",
"projective_transform_by_points",
"(",
"x",
",",
"src",
",",
"dst",
",",
"map_args",
"=",
"None",
",",
"output_shape",
"=",
"None",
",",
"order",
"=",
"1",
",",
"mode",
"=",
"'constant'",
",",
"cval",
"=",
"0.0",
",",
"clip",
"=",
"True",
",",
"preserve_range",
"=",
"False",
")",
":",
"if",
"map_args",
"is",
"None",
":",
"map_args",
"=",
"{",
"}",
"# if type(src) is list:",
"if",
"isinstance",
"(",
"src",
",",
"list",
")",
":",
"# convert to numpy",
"src",
"=",
"np",
".",
"array",
"(",
"src",
")",
"# if type(dst) is list:",
"if",
"isinstance",
"(",
"dst",
",",
"list",
")",
":",
"dst",
"=",
"np",
".",
"array",
"(",
"dst",
")",
"if",
"np",
".",
"max",
"(",
"x",
")",
">",
"1",
":",
"# convert to [0, 1]",
"x",
"=",
"x",
"/",
"255",
"m",
"=",
"transform",
".",
"ProjectiveTransform",
"(",
")",
"m",
".",
"estimate",
"(",
"dst",
",",
"src",
")",
"warped",
"=",
"transform",
".",
"warp",
"(",
"x",
",",
"m",
",",
"map_args",
"=",
"map_args",
",",
"output_shape",
"=",
"output_shape",
",",
"order",
"=",
"order",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"cval",
",",
"clip",
"=",
"clip",
",",
"preserve_range",
"=",
"preserve_range",
")",
"return",
"warped"
] | Projective transform by given coordinates, usually 4 coordinates.
see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
src : list or numpy
The original coordinates, usually 4 coordinates of (width, height).
dst : list or numpy
The coordinates after transformation, the number of coordinates is the same with src.
map_args : dictionary or None
Keyword arguments passed to inverse map.
output_shape : tuple of 2 int
Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified.
order : int
The order of interpolation. The order has to be in the range 0-5:
- 0 Nearest-neighbor
- 1 Bi-linear (default)
- 2 Bi-quadratic
- 3 Bi-cubic
- 4 Bi-quartic
- 5 Bi-quintic
mode : str
One of `constant` (default), `edge`, `symmetric`, `reflect` or `wrap`.
Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad.
cval : float
Used in conjunction with mode `constant`, the value outside the image boundaries.
clip : boolean
Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
preserve_range : boolean
Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.
Returns
-------
numpy.array
A processed image.
Examples
--------
Assume X is an image from CIFAR-10, i.e. shape == (32, 32, 3)
>>> src = [[0,0],[0,32],[32,0],[32,32]] # [w, h]
>>> dst = [[10,10],[0,32],[32,0],[32,32]]
>>> x = tl.prepro.projective_transform_by_points(X, src, dst)
References
-----------
- `scikit-image : geometric transformations <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__
- `scikit-image : examples <http://scikit-image.org/docs/dev/auto_examples/index.html>`__ | [
"Projective",
"transform",
"by",
"given",
"coordinates",
"usually",
"4",
"coordinates",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L631-L705 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | rotation | def rotation(
x, rg=20, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1
):
"""Rotate an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
rg : int or float
Degree to rotate, usually 0 ~ 180.
is_random : boolean
If True, randomly rotate. Default is False
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode=`constant`. Default is 0.0
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x --> [row, col, 1]
>>> x = tl.prepro.rotation(x, rg=40, is_random=False)
>>> tl.vis.save_image(x, 'im.png')
"""
if is_random:
theta = np.pi / 180 * np.random.uniform(-rg, rg)
else:
theta = np.pi / 180 * rg
rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]])
h, w = x.shape[row_index], x.shape[col_index]
transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)
x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | python | def rotation(
x, rg=20, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1
):
"""Rotate an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
rg : int or float
Degree to rotate, usually 0 ~ 180.
is_random : boolean
If True, randomly rotate. Default is False
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode=`constant`. Default is 0.0
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x --> [row, col, 1]
>>> x = tl.prepro.rotation(x, rg=40, is_random=False)
>>> tl.vis.save_image(x, 'im.png')
"""
if is_random:
theta = np.pi / 180 * np.random.uniform(-rg, rg)
else:
theta = np.pi / 180 * rg
rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]])
h, w = x.shape[row_index], x.shape[col_index]
transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)
x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | [
"def",
"rotation",
"(",
"x",
",",
"rg",
"=",
"20",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
",",
"channel_index",
"=",
"2",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
",",
"order",
"=",
"1",
")",
":",
"if",
"is_random",
":",
"theta",
"=",
"np",
".",
"pi",
"/",
"180",
"*",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"rg",
",",
"rg",
")",
"else",
":",
"theta",
"=",
"np",
".",
"pi",
"/",
"180",
"*",
"rg",
"rotation_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"np",
".",
"sin",
"(",
"theta",
")",
",",
"np",
".",
"cos",
"(",
"theta",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"row_index",
"]",
",",
"x",
".",
"shape",
"[",
"col_index",
"]",
"transform_matrix",
"=",
"transform_matrix_offset_center",
"(",
"rotation_matrix",
",",
"h",
",",
"w",
")",
"x",
"=",
"affine_transform",
"(",
"x",
",",
"transform_matrix",
",",
"channel_index",
",",
"fill_mode",
",",
"cval",
",",
"order",
")",
"return",
"x"
] | Rotate an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
rg : int or float
Degree to rotate, usually 0 ~ 180.
is_random : boolean
If True, randomly rotate. Default is False
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode=`constant`. Default is 0.0
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x --> [row, col, 1]
>>> x = tl.prepro.rotation(x, rg=40, is_random=False)
>>> tl.vis.save_image(x, 'im.png') | [
"Rotate",
"an",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L709-L752 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | crop | def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1):
"""Randomly or centrally crop an image.
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
wrg : int
Size of width.
hrg : int
Size of height.
is_random : boolean,
If True, randomly crop, else central crop. Default is False.
row_index: int
index of row.
col_index: int
index of column.
Returns
-------
numpy.array
A processed image.
"""
h, w = x.shape[row_index], x.shape[col_index]
if (h < hrg) or (w < wrg):
raise AssertionError("The size of cropping should smaller than or equal to the original image")
if is_random:
h_offset = int(np.random.uniform(0, h - hrg))
w_offset = int(np.random.uniform(0, w - wrg))
# tl.logging.info(h_offset, w_offset, x[h_offset: hrg+h_offset ,w_offset: wrg+w_offset].shape)
return x[h_offset:hrg + h_offset, w_offset:wrg + w_offset]
else: # central crop
h_offset = int(np.floor((h - hrg) / 2.))
w_offset = int(np.floor((w - wrg) / 2.))
h_end = h_offset + hrg
w_end = w_offset + wrg
return x[h_offset:h_end, w_offset:w_end] | python | def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1):
"""Randomly or centrally crop an image.
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
wrg : int
Size of width.
hrg : int
Size of height.
is_random : boolean,
If True, randomly crop, else central crop. Default is False.
row_index: int
index of row.
col_index: int
index of column.
Returns
-------
numpy.array
A processed image.
"""
h, w = x.shape[row_index], x.shape[col_index]
if (h < hrg) or (w < wrg):
raise AssertionError("The size of cropping should smaller than or equal to the original image")
if is_random:
h_offset = int(np.random.uniform(0, h - hrg))
w_offset = int(np.random.uniform(0, w - wrg))
# tl.logging.info(h_offset, w_offset, x[h_offset: hrg+h_offset ,w_offset: wrg+w_offset].shape)
return x[h_offset:hrg + h_offset, w_offset:wrg + w_offset]
else: # central crop
h_offset = int(np.floor((h - hrg) / 2.))
w_offset = int(np.floor((w - wrg) / 2.))
h_end = h_offset + hrg
w_end = w_offset + wrg
return x[h_offset:h_end, w_offset:w_end] | [
"def",
"crop",
"(",
"x",
",",
"wrg",
",",
"hrg",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
")",
":",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"row_index",
"]",
",",
"x",
".",
"shape",
"[",
"col_index",
"]",
"if",
"(",
"h",
"<",
"hrg",
")",
"or",
"(",
"w",
"<",
"wrg",
")",
":",
"raise",
"AssertionError",
"(",
"\"The size of cropping should smaller than or equal to the original image\"",
")",
"if",
"is_random",
":",
"h_offset",
"=",
"int",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"h",
"-",
"hrg",
")",
")",
"w_offset",
"=",
"int",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"w",
"-",
"wrg",
")",
")",
"# tl.logging.info(h_offset, w_offset, x[h_offset: hrg+h_offset ,w_offset: wrg+w_offset].shape)",
"return",
"x",
"[",
"h_offset",
":",
"hrg",
"+",
"h_offset",
",",
"w_offset",
":",
"wrg",
"+",
"w_offset",
"]",
"else",
":",
"# central crop",
"h_offset",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"(",
"h",
"-",
"hrg",
")",
"/",
"2.",
")",
")",
"w_offset",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"(",
"w",
"-",
"wrg",
")",
"/",
"2.",
")",
")",
"h_end",
"=",
"h_offset",
"+",
"hrg",
"w_end",
"=",
"w_offset",
"+",
"wrg",
"return",
"x",
"[",
"h_offset",
":",
"h_end",
",",
"w_offset",
":",
"w_end",
"]"
] | Randomly or centrally crop an image.
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
wrg : int
Size of width.
hrg : int
Size of height.
is_random : boolean,
If True, randomly crop, else central crop. Default is False.
row_index: int
index of row.
col_index: int
index of column.
Returns
-------
numpy.array
A processed image. | [
"Randomly",
"or",
"centrally",
"crop",
"an",
"image",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L794-L833 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | crop_multi | def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1):
"""Randomly or centrally crop multiple images.
Parameters
----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.crop``.
Returns
-------
numpy.array
A list of processed images.
"""
h, w = x[0].shape[row_index], x[0].shape[col_index]
if (h < hrg) or (w < wrg):
raise AssertionError("The size of cropping should smaller than or equal to the original image")
if is_random:
h_offset = int(np.random.uniform(0, h - hrg))
w_offset = int(np.random.uniform(0, w - wrg))
results = []
for data in x:
results.append(data[h_offset:hrg + h_offset, w_offset:wrg + w_offset])
return np.asarray(results)
else:
# central crop
h_offset = (h - hrg) / 2
w_offset = (w - wrg) / 2
results = []
for data in x:
results.append(data[h_offset:h - h_offset, w_offset:w - w_offset])
return np.asarray(results) | python | def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1):
"""Randomly or centrally crop multiple images.
Parameters
----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.crop``.
Returns
-------
numpy.array
A list of processed images.
"""
h, w = x[0].shape[row_index], x[0].shape[col_index]
if (h < hrg) or (w < wrg):
raise AssertionError("The size of cropping should smaller than or equal to the original image")
if is_random:
h_offset = int(np.random.uniform(0, h - hrg))
w_offset = int(np.random.uniform(0, w - wrg))
results = []
for data in x:
results.append(data[h_offset:hrg + h_offset, w_offset:wrg + w_offset])
return np.asarray(results)
else:
# central crop
h_offset = (h - hrg) / 2
w_offset = (w - wrg) / 2
results = []
for data in x:
results.append(data[h_offset:h - h_offset, w_offset:w - w_offset])
return np.asarray(results) | [
"def",
"crop_multi",
"(",
"x",
",",
"wrg",
",",
"hrg",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
")",
":",
"h",
",",
"w",
"=",
"x",
"[",
"0",
"]",
".",
"shape",
"[",
"row_index",
"]",
",",
"x",
"[",
"0",
"]",
".",
"shape",
"[",
"col_index",
"]",
"if",
"(",
"h",
"<",
"hrg",
")",
"or",
"(",
"w",
"<",
"wrg",
")",
":",
"raise",
"AssertionError",
"(",
"\"The size of cropping should smaller than or equal to the original image\"",
")",
"if",
"is_random",
":",
"h_offset",
"=",
"int",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"h",
"-",
"hrg",
")",
")",
"w_offset",
"=",
"int",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"w",
"-",
"wrg",
")",
")",
"results",
"=",
"[",
"]",
"for",
"data",
"in",
"x",
":",
"results",
".",
"append",
"(",
"data",
"[",
"h_offset",
":",
"hrg",
"+",
"h_offset",
",",
"w_offset",
":",
"wrg",
"+",
"w_offset",
"]",
")",
"return",
"np",
".",
"asarray",
"(",
"results",
")",
"else",
":",
"# central crop",
"h_offset",
"=",
"(",
"h",
"-",
"hrg",
")",
"/",
"2",
"w_offset",
"=",
"(",
"w",
"-",
"wrg",
")",
"/",
"2",
"results",
"=",
"[",
"]",
"for",
"data",
"in",
"x",
":",
"results",
".",
"append",
"(",
"data",
"[",
"h_offset",
":",
"h",
"-",
"h_offset",
",",
"w_offset",
":",
"w",
"-",
"w_offset",
"]",
")",
"return",
"np",
".",
"asarray",
"(",
"results",
")"
] | Randomly or centrally crop multiple images.
Parameters
----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.crop``.
Returns
-------
numpy.array
A list of processed images. | [
"Randomly",
"or",
"centrally",
"crop",
"multiple",
"images",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L842-L877 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | flip_axis | def flip_axis(x, axis=1, is_random=False):
"""Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly,
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
axis : int
Which axis to flip.
- 0, flip up and down
- 1, flip left and right
- 2, flip channel
is_random : boolean
If True, randomly flip. Default is False.
Returns
-------
numpy.array
A processed image.
"""
if is_random:
factor = np.random.uniform(-1, 1)
if factor > 0:
x = np.asarray(x).swapaxes(axis, 0)
x = x[::-1, ...]
x = x.swapaxes(0, axis)
return x
else:
return x
else:
x = np.asarray(x).swapaxes(axis, 0)
x = x[::-1, ...]
x = x.swapaxes(0, axis)
return x | python | def flip_axis(x, axis=1, is_random=False):
"""Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly,
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
axis : int
Which axis to flip.
- 0, flip up and down
- 1, flip left and right
- 2, flip channel
is_random : boolean
If True, randomly flip. Default is False.
Returns
-------
numpy.array
A processed image.
"""
if is_random:
factor = np.random.uniform(-1, 1)
if factor > 0:
x = np.asarray(x).swapaxes(axis, 0)
x = x[::-1, ...]
x = x.swapaxes(0, axis)
return x
else:
return x
else:
x = np.asarray(x).swapaxes(axis, 0)
x = x[::-1, ...]
x = x.swapaxes(0, axis)
return x | [
"def",
"flip_axis",
"(",
"x",
",",
"axis",
"=",
"1",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"is_random",
":",
"factor",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
")",
"if",
"factor",
">",
"0",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
".",
"swapaxes",
"(",
"axis",
",",
"0",
")",
"x",
"=",
"x",
"[",
":",
":",
"-",
"1",
",",
"...",
"]",
"x",
"=",
"x",
".",
"swapaxes",
"(",
"0",
",",
"axis",
")",
"return",
"x",
"else",
":",
"return",
"x",
"else",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
".",
"swapaxes",
"(",
"axis",
",",
"0",
")",
"x",
"=",
"x",
"[",
":",
":",
"-",
"1",
",",
"...",
"]",
"x",
"=",
"x",
".",
"swapaxes",
"(",
"0",
",",
"axis",
")",
"return",
"x"
] | Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly,
Parameters
----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
axis : int
Which axis to flip.
- 0, flip up and down
- 1, flip left and right
- 2, flip channel
is_random : boolean
If True, randomly flip. Default is False.
Returns
-------
numpy.array
A processed image. | [
"Flip",
"the",
"axis",
"of",
"an",
"image",
"such",
"as",
"flip",
"left",
"and",
"right",
"up",
"and",
"down",
"randomly",
"or",
"non",
"-",
"randomly"
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L881-L915 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | flip_axis_multi | def flip_axis_multi(x, axis, is_random=False):
"""Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.flip_axis``.
Returns
-------
numpy.array
A list of processed images.
"""
if is_random:
factor = np.random.uniform(-1, 1)
if factor > 0:
# x = np.asarray(x).swapaxes(axis, 0)
# x = x[::-1, ...]
# x = x.swapaxes(0, axis)
# return x
results = []
for data in x:
data = np.asarray(data).swapaxes(axis, 0)
data = data[::-1, ...]
data = data.swapaxes(0, axis)
results.append(data)
return np.asarray(results)
else:
return np.asarray(x)
else:
# x = np.asarray(x).swapaxes(axis, 0)
# x = x[::-1, ...]
# x = x.swapaxes(0, axis)
# return x
results = []
for data in x:
data = np.asarray(data).swapaxes(axis, 0)
data = data[::-1, ...]
data = data.swapaxes(0, axis)
results.append(data)
return np.asarray(results) | python | def flip_axis_multi(x, axis, is_random=False):
"""Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.flip_axis``.
Returns
-------
numpy.array
A list of processed images.
"""
if is_random:
factor = np.random.uniform(-1, 1)
if factor > 0:
# x = np.asarray(x).swapaxes(axis, 0)
# x = x[::-1, ...]
# x = x.swapaxes(0, axis)
# return x
results = []
for data in x:
data = np.asarray(data).swapaxes(axis, 0)
data = data[::-1, ...]
data = data.swapaxes(0, axis)
results.append(data)
return np.asarray(results)
else:
return np.asarray(x)
else:
# x = np.asarray(x).swapaxes(axis, 0)
# x = x[::-1, ...]
# x = x.swapaxes(0, axis)
# return x
results = []
for data in x:
data = np.asarray(data).swapaxes(axis, 0)
data = data[::-1, ...]
data = data.swapaxes(0, axis)
results.append(data)
return np.asarray(results) | [
"def",
"flip_axis_multi",
"(",
"x",
",",
"axis",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"is_random",
":",
"factor",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
")",
"if",
"factor",
">",
"0",
":",
"# x = np.asarray(x).swapaxes(axis, 0)",
"# x = x[::-1, ...]",
"# x = x.swapaxes(0, axis)",
"# return x",
"results",
"=",
"[",
"]",
"for",
"data",
"in",
"x",
":",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
".",
"swapaxes",
"(",
"axis",
",",
"0",
")",
"data",
"=",
"data",
"[",
":",
":",
"-",
"1",
",",
"...",
"]",
"data",
"=",
"data",
".",
"swapaxes",
"(",
"0",
",",
"axis",
")",
"results",
".",
"append",
"(",
"data",
")",
"return",
"np",
".",
"asarray",
"(",
"results",
")",
"else",
":",
"return",
"np",
".",
"asarray",
"(",
"x",
")",
"else",
":",
"# x = np.asarray(x).swapaxes(axis, 0)",
"# x = x[::-1, ...]",
"# x = x.swapaxes(0, axis)",
"# return x",
"results",
"=",
"[",
"]",
"for",
"data",
"in",
"x",
":",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
".",
"swapaxes",
"(",
"axis",
",",
"0",
")",
"data",
"=",
"data",
"[",
":",
":",
"-",
"1",
",",
"...",
"]",
"data",
"=",
"data",
".",
"swapaxes",
"(",
"0",
",",
"axis",
")",
"results",
".",
"append",
"(",
"data",
")",
"return",
"np",
".",
"asarray",
"(",
"results",
")"
] | Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly,
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.flip_axis``.
Returns
-------
numpy.array
A list of processed images. | [
"Flip",
"the",
"axises",
"of",
"multiple",
"images",
"together",
"such",
"as",
"flip",
"left",
"and",
"right",
"up",
"and",
"down",
"randomly",
"or",
"non",
"-",
"randomly"
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L918-L961 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | shift | def shift(
x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shift an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
wrg : float
Percentage of shift in axis x, usually -0.25 ~ 0.25.
hrg : float
Percentage of shift in axis y, usually -0.25 ~ 0.25.
is_random : boolean
If True, randomly shift. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
"""
h, w = x.shape[row_index], x.shape[col_index]
if is_random:
tx = np.random.uniform(-hrg, hrg) * h
ty = np.random.uniform(-wrg, wrg) * w
else:
tx, ty = hrg * h, wrg * w
translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | python | def shift(
x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shift an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
wrg : float
Percentage of shift in axis x, usually -0.25 ~ 0.25.
hrg : float
Percentage of shift in axis y, usually -0.25 ~ 0.25.
is_random : boolean
If True, randomly shift. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
"""
h, w = x.shape[row_index], x.shape[col_index]
if is_random:
tx = np.random.uniform(-hrg, hrg) * h
ty = np.random.uniform(-wrg, wrg) * w
else:
tx, ty = hrg * h, wrg * w
translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | [
"def",
"shift",
"(",
"x",
",",
"wrg",
"=",
"0.1",
",",
"hrg",
"=",
"0.1",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
",",
"channel_index",
"=",
"2",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
",",
"order",
"=",
"1",
")",
":",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"row_index",
"]",
",",
"x",
".",
"shape",
"[",
"col_index",
"]",
"if",
"is_random",
":",
"tx",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"hrg",
",",
"hrg",
")",
"*",
"h",
"ty",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"wrg",
",",
"wrg",
")",
"*",
"w",
"else",
":",
"tx",
",",
"ty",
"=",
"hrg",
"*",
"h",
",",
"wrg",
"*",
"w",
"translation_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"tx",
"]",
",",
"[",
"0",
",",
"1",
",",
"ty",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"transform_matrix",
"=",
"translation_matrix",
"# no need to do offset",
"x",
"=",
"affine_transform",
"(",
"x",
",",
"transform_matrix",
",",
"channel_index",
",",
"fill_mode",
",",
"cval",
",",
"order",
")",
"return",
"x"
] | Shift an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
wrg : float
Percentage of shift in axis x, usually -0.25 ~ 0.25.
hrg : float
Percentage of shift in axis y, usually -0.25 ~ 0.25.
is_random : boolean
If True, randomly shift. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image. | [
"Shift",
"an",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L965-L1006 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | shift_multi | def shift_multi(
x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shift images with the same arguments, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.shift``.
Returns
-------
numpy.array
A list of processed images.
"""
h, w = x[0].shape[row_index], x[0].shape[col_index]
if is_random:
tx = np.random.uniform(-hrg, hrg) * h
ty = np.random.uniform(-wrg, wrg) * w
else:
tx, ty = hrg * h, wrg * w
translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
results = []
for data in x:
results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order))
return np.asarray(results) | python | def shift_multi(
x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shift images with the same arguments, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.shift``.
Returns
-------
numpy.array
A list of processed images.
"""
h, w = x[0].shape[row_index], x[0].shape[col_index]
if is_random:
tx = np.random.uniform(-hrg, hrg) * h
ty = np.random.uniform(-wrg, wrg) * w
else:
tx, ty = hrg * h, wrg * w
translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
results = []
for data in x:
results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order))
return np.asarray(results) | [
"def",
"shift_multi",
"(",
"x",
",",
"wrg",
"=",
"0.1",
",",
"hrg",
"=",
"0.1",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
",",
"channel_index",
"=",
"2",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
",",
"order",
"=",
"1",
")",
":",
"h",
",",
"w",
"=",
"x",
"[",
"0",
"]",
".",
"shape",
"[",
"row_index",
"]",
",",
"x",
"[",
"0",
"]",
".",
"shape",
"[",
"col_index",
"]",
"if",
"is_random",
":",
"tx",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"hrg",
",",
"hrg",
")",
"*",
"h",
"ty",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"wrg",
",",
"wrg",
")",
"*",
"w",
"else",
":",
"tx",
",",
"ty",
"=",
"hrg",
"*",
"h",
",",
"wrg",
"*",
"w",
"translation_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"tx",
"]",
",",
"[",
"0",
",",
"1",
",",
"ty",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"transform_matrix",
"=",
"translation_matrix",
"# no need to do offset",
"results",
"=",
"[",
"]",
"for",
"data",
"in",
"x",
":",
"results",
".",
"append",
"(",
"affine_transform",
"(",
"data",
",",
"transform_matrix",
",",
"channel_index",
",",
"fill_mode",
",",
"cval",
",",
"order",
")",
")",
"return",
"np",
".",
"asarray",
"(",
"results",
")"
] | Shift images with the same arguments, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.shift``.
Returns
-------
numpy.array
A list of processed images. | [
"Shift",
"images",
"with",
"the",
"same",
"arguments",
"randomly",
"or",
"non",
"-",
"randomly",
".",
"Usually",
"be",
"used",
"for",
"image",
"segmentation",
"which",
"x",
"=",
"[",
"X",
"Y",
"]",
"X",
"and",
"Y",
"should",
"be",
"matched",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1009-L1041 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | shear | def shear(
x, intensity=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shear an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
intensity : float
Percentage of shear, usually -0.5 ~ 0.5 (is_random==True), 0 ~ 0.5 (is_random==False),
you can have a quick try by shear(X, 1).
is_random : boolean
If True, randomly shear. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
References
-----------
- `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__
"""
if is_random:
shear = np.random.uniform(-intensity, intensity)
else:
shear = intensity
shear_matrix = np.array([[1, -np.sin(shear), 0], [0, np.cos(shear), 0], [0, 0, 1]])
h, w = x.shape[row_index], x.shape[col_index]
transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)
x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | python | def shear(
x, intensity=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shear an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
intensity : float
Percentage of shear, usually -0.5 ~ 0.5 (is_random==True), 0 ~ 0.5 (is_random==False),
you can have a quick try by shear(X, 1).
is_random : boolean
If True, randomly shear. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
References
-----------
- `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__
"""
if is_random:
shear = np.random.uniform(-intensity, intensity)
else:
shear = intensity
shear_matrix = np.array([[1, -np.sin(shear), 0], [0, np.cos(shear), 0], [0, 0, 1]])
h, w = x.shape[row_index], x.shape[col_index]
transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)
x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | [
"def",
"shear",
"(",
"x",
",",
"intensity",
"=",
"0.1",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
",",
"channel_index",
"=",
"2",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
",",
"order",
"=",
"1",
")",
":",
"if",
"is_random",
":",
"shear",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"intensity",
",",
"intensity",
")",
"else",
":",
"shear",
"=",
"intensity",
"shear_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"-",
"np",
".",
"sin",
"(",
"shear",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"np",
".",
"cos",
"(",
"shear",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"row_index",
"]",
",",
"x",
".",
"shape",
"[",
"col_index",
"]",
"transform_matrix",
"=",
"transform_matrix_offset_center",
"(",
"shear_matrix",
",",
"h",
",",
"w",
")",
"x",
"=",
"affine_transform",
"(",
"x",
",",
"transform_matrix",
",",
"channel_index",
",",
"fill_mode",
",",
"cval",
",",
"order",
")",
"return",
"x"
] | Shear an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
intensity : float
Percentage of shear, usually -0.5 ~ 0.5 (is_random==True), 0 ~ 0.5 (is_random==False),
you can have a quick try by shear(X, 1).
is_random : boolean
If True, randomly shear. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
References
-----------
- `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__ | [
"Shear",
"an",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1045-L1088 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | shear2 | def shear2(
x, shear=(0.1, 0.1), is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shear an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
shear : tuple of two floats
Percentage of shear for height and width direction (0, 1).
is_random : boolean
If True, randomly shear. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
References
-----------
- `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__
"""
if len(shear) != 2:
raise AssertionError(
"shear should be tuple of 2 floats, or you want to use tl.prepro.shear rather than tl.prepro.shear2 ?"
)
if isinstance(shear, tuple):
shear = list(shear)
if is_random:
shear[0] = np.random.uniform(-shear[0], shear[0])
shear[1] = np.random.uniform(-shear[1], shear[1])
shear_matrix = np.array([[1, shear[0], 0], \
[shear[1], 1, 0], \
[0, 0, 1]])
h, w = x.shape[row_index], x.shape[col_index]
transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)
x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | python | def shear2(
x, shear=(0.1, 0.1), is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shear an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
shear : tuple of two floats
Percentage of shear for height and width direction (0, 1).
is_random : boolean
If True, randomly shear. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
References
-----------
- `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__
"""
if len(shear) != 2:
raise AssertionError(
"shear should be tuple of 2 floats, or you want to use tl.prepro.shear rather than tl.prepro.shear2 ?"
)
if isinstance(shear, tuple):
shear = list(shear)
if is_random:
shear[0] = np.random.uniform(-shear[0], shear[0])
shear[1] = np.random.uniform(-shear[1], shear[1])
shear_matrix = np.array([[1, shear[0], 0], \
[shear[1], 1, 0], \
[0, 0, 1]])
h, w = x.shape[row_index], x.shape[col_index]
transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)
x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | [
"def",
"shear2",
"(",
"x",
",",
"shear",
"=",
"(",
"0.1",
",",
"0.1",
")",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
",",
"channel_index",
"=",
"2",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
",",
"order",
"=",
"1",
")",
":",
"if",
"len",
"(",
"shear",
")",
"!=",
"2",
":",
"raise",
"AssertionError",
"(",
"\"shear should be tuple of 2 floats, or you want to use tl.prepro.shear rather than tl.prepro.shear2 ?\"",
")",
"if",
"isinstance",
"(",
"shear",
",",
"tuple",
")",
":",
"shear",
"=",
"list",
"(",
"shear",
")",
"if",
"is_random",
":",
"shear",
"[",
"0",
"]",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"shear",
"[",
"0",
"]",
",",
"shear",
"[",
"0",
"]",
")",
"shear",
"[",
"1",
"]",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"shear",
"[",
"1",
"]",
",",
"shear",
"[",
"1",
"]",
")",
"shear_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"shear",
"[",
"0",
"]",
",",
"0",
"]",
",",
"[",
"shear",
"[",
"1",
"]",
",",
"1",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"row_index",
"]",
",",
"x",
".",
"shape",
"[",
"col_index",
"]",
"transform_matrix",
"=",
"transform_matrix_offset_center",
"(",
"shear_matrix",
",",
"h",
",",
"w",
")",
"x",
"=",
"affine_transform",
"(",
"x",
",",
"transform_matrix",
",",
"channel_index",
",",
"fill_mode",
",",
"cval",
",",
"order",
")",
"return",
"x"
] | Shear an image randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
shear : tuple of two floats
Percentage of shear for height and width direction (0, 1).
is_random : boolean
If True, randomly shear. Default is False.
row_index col_index and channel_index : int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
fill_mode : str
Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
cval : float
Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0.
order : int
The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__
Returns
-------
numpy.array
A processed image.
References
-----------
- `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__ | [
"Shear",
"an",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1125-L1175 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | swirl | def swirl(
x, center=None, strength=1, radius=100, rotation=0, output_shape=None, order=1, mode='constant', cval=0,
clip=True, preserve_range=False, is_random=False
):
"""Swirl an image randomly or non-randomly, see `scikit-image swirl API <http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.swirl>`__
and `example <http://scikit-image.org/docs/dev/auto_examples/plot_swirl.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
center : tuple or 2 int or None
Center coordinate of transformation (optional).
strength : float
The amount of swirling applied.
radius : float
The extent of the swirl in pixels. The effect dies out rapidly beyond radius.
rotation : float
Additional rotation applied to the image, usually [0, 360], relates to center.
output_shape : tuple of 2 int or None
Shape of the output image generated (height, width). By default the shape of the input image is preserved.
order : int, optional
The order of the spline interpolation, default is 1. The order has to be in the range 0-5. See skimage.transform.warp for detail.
mode : str
One of `constant` (default), `edge`, `symmetric` `reflect` and `wrap`.
Points outside the boundaries of the input are filled according to the given mode, with `constant` used as the default. Modes match the behaviour of numpy.pad.
cval : float
Used in conjunction with mode `constant`, the value outside the image boundaries.
clip : boolean
Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
preserve_range : boolean
Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.
is_random : boolean,
If True, random swirl. Default is False.
- random center = [(0 ~ x.shape[0]), (0 ~ x.shape[1])]
- random strength = [0, strength]
- random radius = [1e-10, radius]
- random rotation = [-rotation, rotation]
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x --> [row, col, 1] greyscale
>>> x = tl.prepro.swirl(x, strength=4, radius=100)
"""
if radius == 0:
raise AssertionError("Invalid radius value")
rotation = np.pi / 180 * rotation
if is_random:
center_h = int(np.random.uniform(0, x.shape[0]))
center_w = int(np.random.uniform(0, x.shape[1]))
center = (center_h, center_w)
strength = np.random.uniform(0, strength)
radius = np.random.uniform(1e-10, radius)
rotation = np.random.uniform(-rotation, rotation)
max_v = np.max(x)
if max_v > 1: # Note: the input of this fn should be [-1, 1], rescale is required.
x = x / max_v
swirled = skimage.transform.swirl(
x, center=center, strength=strength, radius=radius, rotation=rotation, output_shape=output_shape, order=order,
mode=mode, cval=cval, clip=clip, preserve_range=preserve_range
)
if max_v > 1:
swirled = swirled * max_v
return swirled | python | def swirl(
x, center=None, strength=1, radius=100, rotation=0, output_shape=None, order=1, mode='constant', cval=0,
clip=True, preserve_range=False, is_random=False
):
"""Swirl an image randomly or non-randomly, see `scikit-image swirl API <http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.swirl>`__
and `example <http://scikit-image.org/docs/dev/auto_examples/plot_swirl.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
center : tuple or 2 int or None
Center coordinate of transformation (optional).
strength : float
The amount of swirling applied.
radius : float
The extent of the swirl in pixels. The effect dies out rapidly beyond radius.
rotation : float
Additional rotation applied to the image, usually [0, 360], relates to center.
output_shape : tuple of 2 int or None
Shape of the output image generated (height, width). By default the shape of the input image is preserved.
order : int, optional
The order of the spline interpolation, default is 1. The order has to be in the range 0-5. See skimage.transform.warp for detail.
mode : str
One of `constant` (default), `edge`, `symmetric` `reflect` and `wrap`.
Points outside the boundaries of the input are filled according to the given mode, with `constant` used as the default. Modes match the behaviour of numpy.pad.
cval : float
Used in conjunction with mode `constant`, the value outside the image boundaries.
clip : boolean
Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
preserve_range : boolean
Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.
is_random : boolean,
If True, random swirl. Default is False.
- random center = [(0 ~ x.shape[0]), (0 ~ x.shape[1])]
- random strength = [0, strength]
- random radius = [1e-10, radius]
- random rotation = [-rotation, rotation]
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x --> [row, col, 1] greyscale
>>> x = tl.prepro.swirl(x, strength=4, radius=100)
"""
if radius == 0:
raise AssertionError("Invalid radius value")
rotation = np.pi / 180 * rotation
if is_random:
center_h = int(np.random.uniform(0, x.shape[0]))
center_w = int(np.random.uniform(0, x.shape[1]))
center = (center_h, center_w)
strength = np.random.uniform(0, strength)
radius = np.random.uniform(1e-10, radius)
rotation = np.random.uniform(-rotation, rotation)
max_v = np.max(x)
if max_v > 1: # Note: the input of this fn should be [-1, 1], rescale is required.
x = x / max_v
swirled = skimage.transform.swirl(
x, center=center, strength=strength, radius=radius, rotation=rotation, output_shape=output_shape, order=order,
mode=mode, cval=cval, clip=clip, preserve_range=preserve_range
)
if max_v > 1:
swirled = swirled * max_v
return swirled | [
"def",
"swirl",
"(",
"x",
",",
"center",
"=",
"None",
",",
"strength",
"=",
"1",
",",
"radius",
"=",
"100",
",",
"rotation",
"=",
"0",
",",
"output_shape",
"=",
"None",
",",
"order",
"=",
"1",
",",
"mode",
"=",
"'constant'",
",",
"cval",
"=",
"0",
",",
"clip",
"=",
"True",
",",
"preserve_range",
"=",
"False",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"radius",
"==",
"0",
":",
"raise",
"AssertionError",
"(",
"\"Invalid radius value\"",
")",
"rotation",
"=",
"np",
".",
"pi",
"/",
"180",
"*",
"rotation",
"if",
"is_random",
":",
"center_h",
"=",
"int",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"x",
".",
"shape",
"[",
"0",
"]",
")",
")",
"center_w",
"=",
"int",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"x",
".",
"shape",
"[",
"1",
"]",
")",
")",
"center",
"=",
"(",
"center_h",
",",
"center_w",
")",
"strength",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"strength",
")",
"radius",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"1e-10",
",",
"radius",
")",
"rotation",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"rotation",
",",
"rotation",
")",
"max_v",
"=",
"np",
".",
"max",
"(",
"x",
")",
"if",
"max_v",
">",
"1",
":",
"# Note: the input of this fn should be [-1, 1], rescale is required.",
"x",
"=",
"x",
"/",
"max_v",
"swirled",
"=",
"skimage",
".",
"transform",
".",
"swirl",
"(",
"x",
",",
"center",
"=",
"center",
",",
"strength",
"=",
"strength",
",",
"radius",
"=",
"radius",
",",
"rotation",
"=",
"rotation",
",",
"output_shape",
"=",
"output_shape",
",",
"order",
"=",
"order",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"cval",
",",
"clip",
"=",
"clip",
",",
"preserve_range",
"=",
"preserve_range",
")",
"if",
"max_v",
">",
"1",
":",
"swirled",
"=",
"swirled",
"*",
"max_v",
"return",
"swirled"
] | Swirl an image randomly or non-randomly, see `scikit-image swirl API <http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.swirl>`__
and `example <http://scikit-image.org/docs/dev/auto_examples/plot_swirl.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
center : tuple or 2 int or None
Center coordinate of transformation (optional).
strength : float
The amount of swirling applied.
radius : float
The extent of the swirl in pixels. The effect dies out rapidly beyond radius.
rotation : float
Additional rotation applied to the image, usually [0, 360], relates to center.
output_shape : tuple of 2 int or None
Shape of the output image generated (height, width). By default the shape of the input image is preserved.
order : int, optional
The order of the spline interpolation, default is 1. The order has to be in the range 0-5. See skimage.transform.warp for detail.
mode : str
One of `constant` (default), `edge`, `symmetric` `reflect` and `wrap`.
Points outside the boundaries of the input are filled according to the given mode, with `constant` used as the default. Modes match the behaviour of numpy.pad.
cval : float
Used in conjunction with mode `constant`, the value outside the image boundaries.
clip : boolean
Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.
preserve_range : boolean
Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.
is_random : boolean,
If True, random swirl. Default is False.
- random center = [(0 ~ x.shape[0]), (0 ~ x.shape[1])]
- random strength = [0, strength]
- random radius = [1e-10, radius]
- random rotation = [-rotation, rotation]
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x --> [row, col, 1] greyscale
>>> x = tl.prepro.swirl(x, strength=4, radius=100) | [
"Swirl",
"an",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"see",
"scikit",
"-",
"image",
"swirl",
"API",
"<http",
":",
"//",
"scikit",
"-",
"image",
".",
"org",
"/",
"docs",
"/",
"dev",
"/",
"api",
"/",
"skimage",
".",
"transform",
".",
"html#skimage",
".",
"transform",
".",
"swirl",
">",
"__",
"and",
"example",
"<http",
":",
"//",
"scikit",
"-",
"image",
".",
"org",
"/",
"docs",
"/",
"dev",
"/",
"auto_examples",
"/",
"plot_swirl",
".",
"html",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1219-L1290 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | elastic_transform | def elastic_transform(x, alpha, sigma, mode="constant", cval=0, is_random=False):
"""Elastic transformation for image as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__.
Parameters
-----------
x : numpy.array
A greyscale image.
alpha : float
Alpha value for elastic transformation.
sigma : float or sequence of float
The smaller the sigma, the more transformation. Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.
mode : str
See `scipy.ndimage.filters.gaussian_filter <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.filters.gaussian_filter.html>`__. Default is `constant`.
cval : float,
Used in conjunction with `mode` of `constant`, the value outside the image boundaries.
is_random : boolean
Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x = tl.prepro.elastic_transform(x, alpha=x.shape[1]*3, sigma=x.shape[1]*0.07)
References
------------
- `Github <https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a>`__.
- `Kaggle <https://www.kaggle.com/pscion/ultrasound-nerve-segmentation/elastic-transform-for-data-augmentation-0878921a>`__
"""
if is_random is False:
random_state = np.random.RandomState(None)
else:
random_state = np.random.RandomState(int(time.time()))
#
is_3d = False
if len(x.shape) == 3 and x.shape[-1] == 1:
x = x[:, :, 0]
is_3d = True
elif len(x.shape) == 3 and x.shape[-1] != 1:
raise Exception("Only support greyscale image")
if len(x.shape) != 2:
raise AssertionError("input should be grey-scale image")
shape = x.shape
dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=mode, cval=cval) * alpha
dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=mode, cval=cval) * alpha
x_, y_ = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij')
indices = np.reshape(x_ + dx, (-1, 1)), np.reshape(y_ + dy, (-1, 1))
if is_3d:
return map_coordinates(x, indices, order=1).reshape((shape[0], shape[1], 1))
else:
return map_coordinates(x, indices, order=1).reshape(shape) | python | def elastic_transform(x, alpha, sigma, mode="constant", cval=0, is_random=False):
"""Elastic transformation for image as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__.
Parameters
-----------
x : numpy.array
A greyscale image.
alpha : float
Alpha value for elastic transformation.
sigma : float or sequence of float
The smaller the sigma, the more transformation. Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.
mode : str
See `scipy.ndimage.filters.gaussian_filter <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.filters.gaussian_filter.html>`__. Default is `constant`.
cval : float,
Used in conjunction with `mode` of `constant`, the value outside the image boundaries.
is_random : boolean
Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x = tl.prepro.elastic_transform(x, alpha=x.shape[1]*3, sigma=x.shape[1]*0.07)
References
------------
- `Github <https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a>`__.
- `Kaggle <https://www.kaggle.com/pscion/ultrasound-nerve-segmentation/elastic-transform-for-data-augmentation-0878921a>`__
"""
if is_random is False:
random_state = np.random.RandomState(None)
else:
random_state = np.random.RandomState(int(time.time()))
#
is_3d = False
if len(x.shape) == 3 and x.shape[-1] == 1:
x = x[:, :, 0]
is_3d = True
elif len(x.shape) == 3 and x.shape[-1] != 1:
raise Exception("Only support greyscale image")
if len(x.shape) != 2:
raise AssertionError("input should be grey-scale image")
shape = x.shape
dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=mode, cval=cval) * alpha
dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=mode, cval=cval) * alpha
x_, y_ = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij')
indices = np.reshape(x_ + dx, (-1, 1)), np.reshape(y_ + dy, (-1, 1))
if is_3d:
return map_coordinates(x, indices, order=1).reshape((shape[0], shape[1], 1))
else:
return map_coordinates(x, indices, order=1).reshape(shape) | [
"def",
"elastic_transform",
"(",
"x",
",",
"alpha",
",",
"sigma",
",",
"mode",
"=",
"\"constant\"",
",",
"cval",
"=",
"0",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"is_random",
"is",
"False",
":",
"random_state",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"None",
")",
"else",
":",
"random_state",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"#",
"is_3d",
"=",
"False",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"3",
"and",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"x",
"=",
"x",
"[",
":",
",",
":",
",",
"0",
"]",
"is_3d",
"=",
"True",
"elif",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"3",
"and",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"Only support greyscale image\"",
")",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"!=",
"2",
":",
"raise",
"AssertionError",
"(",
"\"input should be grey-scale image\"",
")",
"shape",
"=",
"x",
".",
"shape",
"dx",
"=",
"gaussian_filter",
"(",
"(",
"random_state",
".",
"rand",
"(",
"*",
"shape",
")",
"*",
"2",
"-",
"1",
")",
",",
"sigma",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"cval",
")",
"*",
"alpha",
"dy",
"=",
"gaussian_filter",
"(",
"(",
"random_state",
".",
"rand",
"(",
"*",
"shape",
")",
"*",
"2",
"-",
"1",
")",
",",
"sigma",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"cval",
")",
"*",
"alpha",
"x_",
",",
"y_",
"=",
"np",
".",
"meshgrid",
"(",
"np",
".",
"arange",
"(",
"shape",
"[",
"0",
"]",
")",
",",
"np",
".",
"arange",
"(",
"shape",
"[",
"1",
"]",
")",
",",
"indexing",
"=",
"'ij'",
")",
"indices",
"=",
"np",
".",
"reshape",
"(",
"x_",
"+",
"dx",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
",",
"np",
".",
"reshape",
"(",
"y_",
"+",
"dy",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
"if",
"is_3d",
":",
"return",
"map_coordinates",
"(",
"x",
",",
"indices",
",",
"order",
"=",
"1",
")",
".",
"reshape",
"(",
"(",
"shape",
"[",
"0",
"]",
",",
"shape",
"[",
"1",
"]",
",",
"1",
")",
")",
"else",
":",
"return",
"map_coordinates",
"(",
"x",
",",
"indices",
",",
"order",
"=",
"1",
")",
".",
"reshape",
"(",
"shape",
")"
] | Elastic transformation for image as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__.
Parameters
-----------
x : numpy.array
A greyscale image.
alpha : float
Alpha value for elastic transformation.
sigma : float or sequence of float
The smaller the sigma, the more transformation. Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes.
mode : str
See `scipy.ndimage.filters.gaussian_filter <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.filters.gaussian_filter.html>`__. Default is `constant`.
cval : float,
Used in conjunction with `mode` of `constant`, the value outside the image boundaries.
is_random : boolean
Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
>>> x = tl.prepro.elastic_transform(x, alpha=x.shape[1]*3, sigma=x.shape[1]*0.07)
References
------------
- `Github <https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a>`__.
- `Kaggle <https://www.kaggle.com/pscion/ultrasound-nerve-segmentation/elastic-transform-for-data-augmentation-0878921a>`__ | [
"Elastic",
"transformation",
"for",
"image",
"as",
"described",
"in",
"[",
"Simard2003",
"]",
"<http",
":",
"//",
"deeplearning",
".",
"cs",
".",
"cmu",
".",
"edu",
"/",
"pdfs",
"/",
"Simard",
".",
"pdf",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1341-L1399 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | zoom | def zoom(x, zoom_range=(0.9, 1.1), flags=None, border_mode='constant'):
"""Zooming/Scaling a single image that height and width are changed together.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
zoom_range : float or tuple of 2 floats
The zooming/scaling ratio, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Returns
-------
numpy.array
A processed image.
"""
zoom_matrix = affine_zoom_matrix(zoom_range=zoom_range)
h, w = x.shape[0], x.shape[1]
transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)
x = affine_transform_cv2(x, transform_matrix, flags=flags, border_mode=border_mode)
return x | python | def zoom(x, zoom_range=(0.9, 1.1), flags=None, border_mode='constant'):
"""Zooming/Scaling a single image that height and width are changed together.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
zoom_range : float or tuple of 2 floats
The zooming/scaling ratio, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Returns
-------
numpy.array
A processed image.
"""
zoom_matrix = affine_zoom_matrix(zoom_range=zoom_range)
h, w = x.shape[0], x.shape[1]
transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)
x = affine_transform_cv2(x, transform_matrix, flags=flags, border_mode=border_mode)
return x | [
"def",
"zoom",
"(",
"x",
",",
"zoom_range",
"=",
"(",
"0.9",
",",
"1.1",
")",
",",
"flags",
"=",
"None",
",",
"border_mode",
"=",
"'constant'",
")",
":",
"zoom_matrix",
"=",
"affine_zoom_matrix",
"(",
"zoom_range",
"=",
"zoom_range",
")",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"x",
".",
"shape",
"[",
"1",
"]",
"transform_matrix",
"=",
"transform_matrix_offset_center",
"(",
"zoom_matrix",
",",
"h",
",",
"w",
")",
"x",
"=",
"affine_transform_cv2",
"(",
"x",
",",
"transform_matrix",
",",
"flags",
"=",
"flags",
",",
"border_mode",
"=",
"border_mode",
")",
"return",
"x"
] | Zooming/Scaling a single image that height and width are changed together.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
zoom_range : float or tuple of 2 floats
The zooming/scaling ratio, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Returns
-------
numpy.array
A processed image. | [
"Zooming",
"/",
"Scaling",
"a",
"single",
"image",
"that",
"height",
"and",
"width",
"are",
"changed",
"together",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1454-L1479 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | respective_zoom | def respective_zoom(x, h_range=(0.9, 1.1), w_range=(0.9, 1.1), flags=None, border_mode='constant'):
"""Zooming/Scaling a single image that height and width are changed independently.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
h_range : float or tuple of 2 floats
The zooming/scaling ratio of height, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
w_range : float or tuple of 2 floats
The zooming/scaling ratio of width, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Returns
-------
numpy.array
A processed image.
"""
zoom_matrix = affine_respective_zoom_matrix(h_range=h_range, w_range=w_range)
h, w = x.shape[0], x.shape[1]
transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)
x = affine_transform_cv2(
x, transform_matrix, flags=flags, border_mode=border_mode
) #affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | python | def respective_zoom(x, h_range=(0.9, 1.1), w_range=(0.9, 1.1), flags=None, border_mode='constant'):
"""Zooming/Scaling a single image that height and width are changed independently.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
h_range : float or tuple of 2 floats
The zooming/scaling ratio of height, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
w_range : float or tuple of 2 floats
The zooming/scaling ratio of width, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Returns
-------
numpy.array
A processed image.
"""
zoom_matrix = affine_respective_zoom_matrix(h_range=h_range, w_range=w_range)
h, w = x.shape[0], x.shape[1]
transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)
x = affine_transform_cv2(
x, transform_matrix, flags=flags, border_mode=border_mode
) #affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)
return x | [
"def",
"respective_zoom",
"(",
"x",
",",
"h_range",
"=",
"(",
"0.9",
",",
"1.1",
")",
",",
"w_range",
"=",
"(",
"0.9",
",",
"1.1",
")",
",",
"flags",
"=",
"None",
",",
"border_mode",
"=",
"'constant'",
")",
":",
"zoom_matrix",
"=",
"affine_respective_zoom_matrix",
"(",
"h_range",
"=",
"h_range",
",",
"w_range",
"=",
"w_range",
")",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"x",
".",
"shape",
"[",
"1",
"]",
"transform_matrix",
"=",
"transform_matrix_offset_center",
"(",
"zoom_matrix",
",",
"h",
",",
"w",
")",
"x",
"=",
"affine_transform_cv2",
"(",
"x",
",",
"transform_matrix",
",",
"flags",
"=",
"flags",
",",
"border_mode",
"=",
"border_mode",
")",
"#affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order)",
"return",
"x"
] | Zooming/Scaling a single image that height and width are changed independently.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
h_range : float or tuple of 2 floats
The zooming/scaling ratio of height, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
w_range : float or tuple of 2 floats
The zooming/scaling ratio of width, greater than 1 means larger.
- float, a fixed ratio.
- tuple of 2 floats, randomly sample a value as the ratio between 2 values.
border_mode : str
- `constant`, pad the image with a constant value (i.e. black or 0)
- `replicate`, the row or column at the very edge of the original is replicated to the extra border.
Returns
-------
numpy.array
A processed image. | [
"Zooming",
"/",
"Scaling",
"a",
"single",
"image",
"that",
"height",
"and",
"width",
"are",
"changed",
"independently",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1482-L1513 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | zoom_multi | def zoom_multi(x, zoom_range=(0.9, 1.1), flags=None, border_mode='constant'):
"""Zoom in and out of images with the same arguments, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.zoom``.
Returns
-------
numpy.array
A list of processed images.
"""
zoom_matrix = affine_zoom_matrix(zoom_range=zoom_range)
results = []
for img in x:
h, w = x.shape[0], x.shape[1]
transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)
results.append(affine_transform_cv2(x, transform_matrix, flags=flags, border_mode=border_mode))
return result | python | def zoom_multi(x, zoom_range=(0.9, 1.1), flags=None, border_mode='constant'):
"""Zoom in and out of images with the same arguments, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.zoom``.
Returns
-------
numpy.array
A list of processed images.
"""
zoom_matrix = affine_zoom_matrix(zoom_range=zoom_range)
results = []
for img in x:
h, w = x.shape[0], x.shape[1]
transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)
results.append(affine_transform_cv2(x, transform_matrix, flags=flags, border_mode=border_mode))
return result | [
"def",
"zoom_multi",
"(",
"x",
",",
"zoom_range",
"=",
"(",
"0.9",
",",
"1.1",
")",
",",
"flags",
"=",
"None",
",",
"border_mode",
"=",
"'constant'",
")",
":",
"zoom_matrix",
"=",
"affine_zoom_matrix",
"(",
"zoom_range",
"=",
"zoom_range",
")",
"results",
"=",
"[",
"]",
"for",
"img",
"in",
"x",
":",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"x",
".",
"shape",
"[",
"1",
"]",
"transform_matrix",
"=",
"transform_matrix_offset_center",
"(",
"zoom_matrix",
",",
"h",
",",
"w",
")",
"results",
".",
"append",
"(",
"affine_transform_cv2",
"(",
"x",
",",
"transform_matrix",
",",
"flags",
"=",
"flags",
",",
"border_mode",
"=",
"border_mode",
")",
")",
"return",
"result"
] | Zoom in and out of images with the same arguments, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.zoom``.
Returns
-------
numpy.array
A list of processed images. | [
"Zoom",
"in",
"and",
"out",
"of",
"images",
"with",
"the",
"same",
"arguments",
"randomly",
"or",
"non",
"-",
"randomly",
".",
"Usually",
"be",
"used",
"for",
"image",
"segmentation",
"which",
"x",
"=",
"[",
"X",
"Y",
"]",
"X",
"and",
"Y",
"should",
"be",
"matched",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1516-L1540 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | brightness | def brightness(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Non negative real number. Default value is 1.
- Small than 1 means brighter.
- If `is_random` is True, gamma in a range of (1-gamma, 1+gamma).
gain : float
The constant multiplier. Default value is 1.
is_random : boolean
If True, randomly change brightness. Default is False.
Returns
-------
numpy.array
A processed image.
References
-----------
- `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`__
- `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`__
"""
if is_random:
gamma = np.random.uniform(1 - gamma, 1 + gamma)
x = exposure.adjust_gamma(x, gamma, gain)
return x | python | def brightness(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Non negative real number. Default value is 1.
- Small than 1 means brighter.
- If `is_random` is True, gamma in a range of (1-gamma, 1+gamma).
gain : float
The constant multiplier. Default value is 1.
is_random : boolean
If True, randomly change brightness. Default is False.
Returns
-------
numpy.array
A processed image.
References
-----------
- `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`__
- `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`__
"""
if is_random:
gamma = np.random.uniform(1 - gamma, 1 + gamma)
x = exposure.adjust_gamma(x, gamma, gain)
return x | [
"def",
"brightness",
"(",
"x",
",",
"gamma",
"=",
"1",
",",
"gain",
"=",
"1",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"is_random",
":",
"gamma",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"1",
"-",
"gamma",
",",
"1",
"+",
"gamma",
")",
"x",
"=",
"exposure",
".",
"adjust_gamma",
"(",
"x",
",",
"gamma",
",",
"gain",
")",
"return",
"x"
] | Change the brightness of a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Non negative real number. Default value is 1.
- Small than 1 means brighter.
- If `is_random` is True, gamma in a range of (1-gamma, 1+gamma).
gain : float
The constant multiplier. Default value is 1.
is_random : boolean
If True, randomly change brightness. Default is False.
Returns
-------
numpy.array
A processed image.
References
-----------
- `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`__
- `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`__ | [
"Change",
"the",
"brightness",
"of",
"a",
"single",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1549-L1579 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | brightness_multi | def brightness_multi(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of multiply images, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpyarray
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.brightness``.
Returns
-------
numpy.array
A list of processed images.
"""
if is_random:
gamma = np.random.uniform(1 - gamma, 1 + gamma)
results = []
for data in x:
results.append(exposure.adjust_gamma(data, gamma, gain))
return np.asarray(results) | python | def brightness_multi(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of multiply images, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpyarray
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.brightness``.
Returns
-------
numpy.array
A list of processed images.
"""
if is_random:
gamma = np.random.uniform(1 - gamma, 1 + gamma)
results = []
for data in x:
results.append(exposure.adjust_gamma(data, gamma, gain))
return np.asarray(results) | [
"def",
"brightness_multi",
"(",
"x",
",",
"gamma",
"=",
"1",
",",
"gain",
"=",
"1",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"is_random",
":",
"gamma",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"1",
"-",
"gamma",
",",
"1",
"+",
"gamma",
")",
"results",
"=",
"[",
"]",
"for",
"data",
"in",
"x",
":",
"results",
".",
"append",
"(",
"exposure",
".",
"adjust_gamma",
"(",
"data",
",",
"gamma",
",",
"gain",
")",
")",
"return",
"np",
".",
"asarray",
"(",
"results",
")"
] | Change the brightness of multiply images, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpyarray
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.brightness``.
Returns
-------
numpy.array
A list of processed images. | [
"Change",
"the",
"brightness",
"of",
"multiply",
"images",
"randomly",
"or",
"non",
"-",
"randomly",
".",
"Usually",
"be",
"used",
"for",
"image",
"segmentation",
"which",
"x",
"=",
"[",
"X",
"Y",
"]",
"X",
"and",
"Y",
"should",
"be",
"matched",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1582-L1605 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | illumination | def illumination(x, gamma=1., contrast=1., saturation=1., is_random=False):
"""Perform illumination augmentation for a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Change brightness (the same with ``tl.prepro.brightness``)
- if is_random=False, one float number, small than one means brighter, greater than one means darker.
- if is_random=True, tuple of two float numbers, (min, max).
contrast : float
Change contrast.
- if is_random=False, one float number, small than one means blur.
- if is_random=True, tuple of two float numbers, (min, max).
saturation : float
Change saturation.
- if is_random=False, one float number, small than one means unsaturation.
- if is_random=True, tuple of two float numbers, (min, max).
is_random : boolean
If True, randomly change illumination. Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
Random
>>> x = tl.prepro.illumination(x, gamma=(0.5, 5.0), contrast=(0.3, 1.0), saturation=(0.7, 1.0), is_random=True)
Non-random
>>> x = tl.prepro.illumination(x, 0.5, 0.6, 0.8, is_random=False)
"""
if is_random:
if not (len(gamma) == len(contrast) == len(saturation) == 2):
raise AssertionError("if is_random = True, the arguments are (min, max)")
## random change brightness # small --> brighter
illum_settings = np.random.randint(0, 3) # 0-brighter, 1-darker, 2 keep normal
if illum_settings == 0: # brighter
gamma = np.random.uniform(gamma[0], 1.0) # (.5, 1.0)
elif illum_settings == 1: # darker
gamma = np.random.uniform(1.0, gamma[1]) # (1.0, 5.0)
else:
gamma = 1
im_ = brightness(x, gamma=gamma, gain=1, is_random=False)
# tl.logging.info("using contrast and saturation")
image = PIL.Image.fromarray(im_) # array -> PIL
contrast_adjust = PIL.ImageEnhance.Contrast(image)
image = contrast_adjust.enhance(np.random.uniform(contrast[0], contrast[1])) #0.3,0.9))
saturation_adjust = PIL.ImageEnhance.Color(image)
image = saturation_adjust.enhance(np.random.uniform(saturation[0], saturation[1])) # (0.7,1.0))
im_ = np.array(image) # PIL -> array
else:
im_ = brightness(x, gamma=gamma, gain=1, is_random=False)
image = PIL.Image.fromarray(im_) # array -> PIL
contrast_adjust = PIL.ImageEnhance.Contrast(image)
image = contrast_adjust.enhance(contrast)
saturation_adjust = PIL.ImageEnhance.Color(image)
image = saturation_adjust.enhance(saturation)
im_ = np.array(image) # PIL -> array
return np.asarray(im_) | python | def illumination(x, gamma=1., contrast=1., saturation=1., is_random=False):
"""Perform illumination augmentation for a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Change brightness (the same with ``tl.prepro.brightness``)
- if is_random=False, one float number, small than one means brighter, greater than one means darker.
- if is_random=True, tuple of two float numbers, (min, max).
contrast : float
Change contrast.
- if is_random=False, one float number, small than one means blur.
- if is_random=True, tuple of two float numbers, (min, max).
saturation : float
Change saturation.
- if is_random=False, one float number, small than one means unsaturation.
- if is_random=True, tuple of two float numbers, (min, max).
is_random : boolean
If True, randomly change illumination. Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
Random
>>> x = tl.prepro.illumination(x, gamma=(0.5, 5.0), contrast=(0.3, 1.0), saturation=(0.7, 1.0), is_random=True)
Non-random
>>> x = tl.prepro.illumination(x, 0.5, 0.6, 0.8, is_random=False)
"""
if is_random:
if not (len(gamma) == len(contrast) == len(saturation) == 2):
raise AssertionError("if is_random = True, the arguments are (min, max)")
## random change brightness # small --> brighter
illum_settings = np.random.randint(0, 3) # 0-brighter, 1-darker, 2 keep normal
if illum_settings == 0: # brighter
gamma = np.random.uniform(gamma[0], 1.0) # (.5, 1.0)
elif illum_settings == 1: # darker
gamma = np.random.uniform(1.0, gamma[1]) # (1.0, 5.0)
else:
gamma = 1
im_ = brightness(x, gamma=gamma, gain=1, is_random=False)
# tl.logging.info("using contrast and saturation")
image = PIL.Image.fromarray(im_) # array -> PIL
contrast_adjust = PIL.ImageEnhance.Contrast(image)
image = contrast_adjust.enhance(np.random.uniform(contrast[0], contrast[1])) #0.3,0.9))
saturation_adjust = PIL.ImageEnhance.Color(image)
image = saturation_adjust.enhance(np.random.uniform(saturation[0], saturation[1])) # (0.7,1.0))
im_ = np.array(image) # PIL -> array
else:
im_ = brightness(x, gamma=gamma, gain=1, is_random=False)
image = PIL.Image.fromarray(im_) # array -> PIL
contrast_adjust = PIL.ImageEnhance.Contrast(image)
image = contrast_adjust.enhance(contrast)
saturation_adjust = PIL.ImageEnhance.Color(image)
image = saturation_adjust.enhance(saturation)
im_ = np.array(image) # PIL -> array
return np.asarray(im_) | [
"def",
"illumination",
"(",
"x",
",",
"gamma",
"=",
"1.",
",",
"contrast",
"=",
"1.",
",",
"saturation",
"=",
"1.",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"is_random",
":",
"if",
"not",
"(",
"len",
"(",
"gamma",
")",
"==",
"len",
"(",
"contrast",
")",
"==",
"len",
"(",
"saturation",
")",
"==",
"2",
")",
":",
"raise",
"AssertionError",
"(",
"\"if is_random = True, the arguments are (min, max)\"",
")",
"## random change brightness # small --> brighter",
"illum_settings",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"3",
")",
"# 0-brighter, 1-darker, 2 keep normal",
"if",
"illum_settings",
"==",
"0",
":",
"# brighter",
"gamma",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"gamma",
"[",
"0",
"]",
",",
"1.0",
")",
"# (.5, 1.0)",
"elif",
"illum_settings",
"==",
"1",
":",
"# darker",
"gamma",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"1.0",
",",
"gamma",
"[",
"1",
"]",
")",
"# (1.0, 5.0)",
"else",
":",
"gamma",
"=",
"1",
"im_",
"=",
"brightness",
"(",
"x",
",",
"gamma",
"=",
"gamma",
",",
"gain",
"=",
"1",
",",
"is_random",
"=",
"False",
")",
"# tl.logging.info(\"using contrast and saturation\")",
"image",
"=",
"PIL",
".",
"Image",
".",
"fromarray",
"(",
"im_",
")",
"# array -> PIL",
"contrast_adjust",
"=",
"PIL",
".",
"ImageEnhance",
".",
"Contrast",
"(",
"image",
")",
"image",
"=",
"contrast_adjust",
".",
"enhance",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"contrast",
"[",
"0",
"]",
",",
"contrast",
"[",
"1",
"]",
")",
")",
"#0.3,0.9))",
"saturation_adjust",
"=",
"PIL",
".",
"ImageEnhance",
".",
"Color",
"(",
"image",
")",
"image",
"=",
"saturation_adjust",
".",
"enhance",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"saturation",
"[",
"0",
"]",
",",
"saturation",
"[",
"1",
"]",
")",
")",
"# (0.7,1.0))",
"im_",
"=",
"np",
".",
"array",
"(",
"image",
")",
"# PIL -> array",
"else",
":",
"im_",
"=",
"brightness",
"(",
"x",
",",
"gamma",
"=",
"gamma",
",",
"gain",
"=",
"1",
",",
"is_random",
"=",
"False",
")",
"image",
"=",
"PIL",
".",
"Image",
".",
"fromarray",
"(",
"im_",
")",
"# array -> PIL",
"contrast_adjust",
"=",
"PIL",
".",
"ImageEnhance",
".",
"Contrast",
"(",
"image",
")",
"image",
"=",
"contrast_adjust",
".",
"enhance",
"(",
"contrast",
")",
"saturation_adjust",
"=",
"PIL",
".",
"ImageEnhance",
".",
"Color",
"(",
"image",
")",
"image",
"=",
"saturation_adjust",
".",
"enhance",
"(",
"saturation",
")",
"im_",
"=",
"np",
".",
"array",
"(",
"image",
")",
"# PIL -> array",
"return",
"np",
".",
"asarray",
"(",
"im_",
")"
] | Perform illumination augmentation for a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Change brightness (the same with ``tl.prepro.brightness``)
- if is_random=False, one float number, small than one means brighter, greater than one means darker.
- if is_random=True, tuple of two float numbers, (min, max).
contrast : float
Change contrast.
- if is_random=False, one float number, small than one means blur.
- if is_random=True, tuple of two float numbers, (min, max).
saturation : float
Change saturation.
- if is_random=False, one float number, small than one means unsaturation.
- if is_random=True, tuple of two float numbers, (min, max).
is_random : boolean
If True, randomly change illumination. Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
Random
>>> x = tl.prepro.illumination(x, gamma=(0.5, 5.0), contrast=(0.3, 1.0), saturation=(0.7, 1.0), is_random=True)
Non-random
>>> x = tl.prepro.illumination(x, 0.5, 0.6, 0.8, is_random=False) | [
"Perform",
"illumination",
"augmentation",
"for",
"a",
"single",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1608-L1678 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | rgb_to_hsv | def rgb_to_hsv(rgb):
"""Input RGB image [0~255] return HSV image [0~1].
Parameters
------------
rgb : numpy.array
An image with values between 0 and 255.
Returns
-------
numpy.array
A processed image.
"""
# Translated from source of colorsys.rgb_to_hsv
# r,g,b should be a numpy arrays with values between 0 and 255
# rgb_to_hsv returns an array of floats between 0.0 and 1.0.
rgb = rgb.astype('float')
hsv = np.zeros_like(rgb)
# in case an RGBA array was passed, just copy the A channel
hsv[..., 3:] = rgb[..., 3:]
r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
maxc = np.max(rgb[..., :3], axis=-1)
minc = np.min(rgb[..., :3], axis=-1)
hsv[..., 2] = maxc
mask = maxc != minc
hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask]
rc = np.zeros_like(r)
gc = np.zeros_like(g)
bc = np.zeros_like(b)
rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask]
gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask]
bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask]
hsv[..., 0] = np.select([r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc)
hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0
return hsv | python | def rgb_to_hsv(rgb):
"""Input RGB image [0~255] return HSV image [0~1].
Parameters
------------
rgb : numpy.array
An image with values between 0 and 255.
Returns
-------
numpy.array
A processed image.
"""
# Translated from source of colorsys.rgb_to_hsv
# r,g,b should be a numpy arrays with values between 0 and 255
# rgb_to_hsv returns an array of floats between 0.0 and 1.0.
rgb = rgb.astype('float')
hsv = np.zeros_like(rgb)
# in case an RGBA array was passed, just copy the A channel
hsv[..., 3:] = rgb[..., 3:]
r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
maxc = np.max(rgb[..., :3], axis=-1)
minc = np.min(rgb[..., :3], axis=-1)
hsv[..., 2] = maxc
mask = maxc != minc
hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask]
rc = np.zeros_like(r)
gc = np.zeros_like(g)
bc = np.zeros_like(b)
rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask]
gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask]
bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask]
hsv[..., 0] = np.select([r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc)
hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0
return hsv | [
"def",
"rgb_to_hsv",
"(",
"rgb",
")",
":",
"# Translated from source of colorsys.rgb_to_hsv",
"# r,g,b should be a numpy arrays with values between 0 and 255",
"# rgb_to_hsv returns an array of floats between 0.0 and 1.0.",
"rgb",
"=",
"rgb",
".",
"astype",
"(",
"'float'",
")",
"hsv",
"=",
"np",
".",
"zeros_like",
"(",
"rgb",
")",
"# in case an RGBA array was passed, just copy the A channel",
"hsv",
"[",
"...",
",",
"3",
":",
"]",
"=",
"rgb",
"[",
"...",
",",
"3",
":",
"]",
"r",
",",
"g",
",",
"b",
"=",
"rgb",
"[",
"...",
",",
"0",
"]",
",",
"rgb",
"[",
"...",
",",
"1",
"]",
",",
"rgb",
"[",
"...",
",",
"2",
"]",
"maxc",
"=",
"np",
".",
"max",
"(",
"rgb",
"[",
"...",
",",
":",
"3",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"minc",
"=",
"np",
".",
"min",
"(",
"rgb",
"[",
"...",
",",
":",
"3",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"hsv",
"[",
"...",
",",
"2",
"]",
"=",
"maxc",
"mask",
"=",
"maxc",
"!=",
"minc",
"hsv",
"[",
"mask",
",",
"1",
"]",
"=",
"(",
"maxc",
"-",
"minc",
")",
"[",
"mask",
"]",
"/",
"maxc",
"[",
"mask",
"]",
"rc",
"=",
"np",
".",
"zeros_like",
"(",
"r",
")",
"gc",
"=",
"np",
".",
"zeros_like",
"(",
"g",
")",
"bc",
"=",
"np",
".",
"zeros_like",
"(",
"b",
")",
"rc",
"[",
"mask",
"]",
"=",
"(",
"maxc",
"-",
"r",
")",
"[",
"mask",
"]",
"/",
"(",
"maxc",
"-",
"minc",
")",
"[",
"mask",
"]",
"gc",
"[",
"mask",
"]",
"=",
"(",
"maxc",
"-",
"g",
")",
"[",
"mask",
"]",
"/",
"(",
"maxc",
"-",
"minc",
")",
"[",
"mask",
"]",
"bc",
"[",
"mask",
"]",
"=",
"(",
"maxc",
"-",
"b",
")",
"[",
"mask",
"]",
"/",
"(",
"maxc",
"-",
"minc",
")",
"[",
"mask",
"]",
"hsv",
"[",
"...",
",",
"0",
"]",
"=",
"np",
".",
"select",
"(",
"[",
"r",
"==",
"maxc",
",",
"g",
"==",
"maxc",
"]",
",",
"[",
"bc",
"-",
"gc",
",",
"2.0",
"+",
"rc",
"-",
"bc",
"]",
",",
"default",
"=",
"4.0",
"+",
"gc",
"-",
"rc",
")",
"hsv",
"[",
"...",
",",
"0",
"]",
"=",
"(",
"hsv",
"[",
"...",
",",
"0",
"]",
"/",
"6.0",
")",
"%",
"1.0",
"return",
"hsv"
] | Input RGB image [0~255] return HSV image [0~1].
Parameters
------------
rgb : numpy.array
An image with values between 0 and 255.
Returns
-------
numpy.array
A processed image. | [
"Input",
"RGB",
"image",
"[",
"0~255",
"]",
"return",
"HSV",
"image",
"[",
"0~1",
"]",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1681-L1716 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | hsv_to_rgb | def hsv_to_rgb(hsv):
"""Input HSV image [0~1] return RGB image [0~255].
Parameters
-------------
hsv : numpy.array
An image with values between 0.0 and 1.0
Returns
-------
numpy.array
A processed image.
"""
# Translated from source of colorsys.hsv_to_rgb
# h,s should be a numpy arrays with values between 0.0 and 1.0
# v should be a numpy array with values between 0.0 and 255.0
# hsv_to_rgb returns an array of uints between 0 and 255.
rgb = np.empty_like(hsv)
rgb[..., 3:] = hsv[..., 3:]
h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
i = (h * 6.0).astype('uint8')
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
i = i % 6
conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5]
rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v)
rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t)
rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p)
return rgb.astype('uint8') | python | def hsv_to_rgb(hsv):
"""Input HSV image [0~1] return RGB image [0~255].
Parameters
-------------
hsv : numpy.array
An image with values between 0.0 and 1.0
Returns
-------
numpy.array
A processed image.
"""
# Translated from source of colorsys.hsv_to_rgb
# h,s should be a numpy arrays with values between 0.0 and 1.0
# v should be a numpy array with values between 0.0 and 255.0
# hsv_to_rgb returns an array of uints between 0 and 255.
rgb = np.empty_like(hsv)
rgb[..., 3:] = hsv[..., 3:]
h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
i = (h * 6.0).astype('uint8')
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
i = i % 6
conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5]
rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v)
rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t)
rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p)
return rgb.astype('uint8') | [
"def",
"hsv_to_rgb",
"(",
"hsv",
")",
":",
"# Translated from source of colorsys.hsv_to_rgb",
"# h,s should be a numpy arrays with values between 0.0 and 1.0",
"# v should be a numpy array with values between 0.0 and 255.0",
"# hsv_to_rgb returns an array of uints between 0 and 255.",
"rgb",
"=",
"np",
".",
"empty_like",
"(",
"hsv",
")",
"rgb",
"[",
"...",
",",
"3",
":",
"]",
"=",
"hsv",
"[",
"...",
",",
"3",
":",
"]",
"h",
",",
"s",
",",
"v",
"=",
"hsv",
"[",
"...",
",",
"0",
"]",
",",
"hsv",
"[",
"...",
",",
"1",
"]",
",",
"hsv",
"[",
"...",
",",
"2",
"]",
"i",
"=",
"(",
"h",
"*",
"6.0",
")",
".",
"astype",
"(",
"'uint8'",
")",
"f",
"=",
"(",
"h",
"*",
"6.0",
")",
"-",
"i",
"p",
"=",
"v",
"*",
"(",
"1.0",
"-",
"s",
")",
"q",
"=",
"v",
"*",
"(",
"1.0",
"-",
"s",
"*",
"f",
")",
"t",
"=",
"v",
"*",
"(",
"1.0",
"-",
"s",
"*",
"(",
"1.0",
"-",
"f",
")",
")",
"i",
"=",
"i",
"%",
"6",
"conditions",
"=",
"[",
"s",
"==",
"0.0",
",",
"i",
"==",
"1",
",",
"i",
"==",
"2",
",",
"i",
"==",
"3",
",",
"i",
"==",
"4",
",",
"i",
"==",
"5",
"]",
"rgb",
"[",
"...",
",",
"0",
"]",
"=",
"np",
".",
"select",
"(",
"conditions",
",",
"[",
"v",
",",
"q",
",",
"p",
",",
"p",
",",
"t",
",",
"v",
"]",
",",
"default",
"=",
"v",
")",
"rgb",
"[",
"...",
",",
"1",
"]",
"=",
"np",
".",
"select",
"(",
"conditions",
",",
"[",
"v",
",",
"v",
",",
"v",
",",
"q",
",",
"p",
",",
"p",
"]",
",",
"default",
"=",
"t",
")",
"rgb",
"[",
"...",
",",
"2",
"]",
"=",
"np",
".",
"select",
"(",
"conditions",
",",
"[",
"v",
",",
"p",
",",
"t",
",",
"v",
",",
"v",
",",
"q",
"]",
",",
"default",
"=",
"p",
")",
"return",
"rgb",
".",
"astype",
"(",
"'uint8'",
")"
] | Input HSV image [0~1] return RGB image [0~255].
Parameters
-------------
hsv : numpy.array
An image with values between 0.0 and 1.0
Returns
-------
numpy.array
A processed image. | [
"Input",
"HSV",
"image",
"[",
"0~1",
"]",
"return",
"RGB",
"image",
"[",
"0~255",
"]",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1719-L1749 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | adjust_hue | def adjust_hue(im, hout=0.66, is_offset=True, is_clip=True, is_random=False):
"""Adjust hue of an RGB image.
This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.
For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.and `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.
Parameters
-----------
im : numpy.array
An image with values between 0 and 255.
hout : float
The scale value for adjusting hue.
- If is_offset is False, set all hue values to this value. 0 is red; 0.33 is green; 0.66 is blue.
- If is_offset is True, add this value as the offset to the hue channel.
is_offset : boolean
Whether `hout` is added on HSV as offset or not. Default is True.
is_clip : boolean
If HSV value smaller than 0, set to 0. Default is True.
is_random : boolean
If True, randomly change hue. Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
Random, add a random value between -0.2 and 0.2 as the offset to every hue values.
>>> im_hue = tl.prepro.adjust_hue(image, hout=0.2, is_offset=True, is_random=False)
Non-random, make all hue to green.
>>> im_green = tl.prepro.adjust_hue(image, hout=0.66, is_offset=False, is_random=False)
References
-----------
- `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.
- `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.
- `StackOverflow: Changing image hue with python PIL <https://stackoverflow.com/questions/7274221/changing-image-hue-with-python-pil>`__.
"""
hsv = rgb_to_hsv(im)
if is_random:
hout = np.random.uniform(-hout, hout)
if is_offset:
hsv[..., 0] += hout
else:
hsv[..., 0] = hout
if is_clip:
hsv[..., 0] = np.clip(hsv[..., 0], 0, np.inf) # Hao : can remove green dots
rgb = hsv_to_rgb(hsv)
return rgb | python | def adjust_hue(im, hout=0.66, is_offset=True, is_clip=True, is_random=False):
"""Adjust hue of an RGB image.
This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.
For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.and `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.
Parameters
-----------
im : numpy.array
An image with values between 0 and 255.
hout : float
The scale value for adjusting hue.
- If is_offset is False, set all hue values to this value. 0 is red; 0.33 is green; 0.66 is blue.
- If is_offset is True, add this value as the offset to the hue channel.
is_offset : boolean
Whether `hout` is added on HSV as offset or not. Default is True.
is_clip : boolean
If HSV value smaller than 0, set to 0. Default is True.
is_random : boolean
If True, randomly change hue. Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
Random, add a random value between -0.2 and 0.2 as the offset to every hue values.
>>> im_hue = tl.prepro.adjust_hue(image, hout=0.2, is_offset=True, is_random=False)
Non-random, make all hue to green.
>>> im_green = tl.prepro.adjust_hue(image, hout=0.66, is_offset=False, is_random=False)
References
-----------
- `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.
- `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.
- `StackOverflow: Changing image hue with python PIL <https://stackoverflow.com/questions/7274221/changing-image-hue-with-python-pil>`__.
"""
hsv = rgb_to_hsv(im)
if is_random:
hout = np.random.uniform(-hout, hout)
if is_offset:
hsv[..., 0] += hout
else:
hsv[..., 0] = hout
if is_clip:
hsv[..., 0] = np.clip(hsv[..., 0], 0, np.inf) # Hao : can remove green dots
rgb = hsv_to_rgb(hsv)
return rgb | [
"def",
"adjust_hue",
"(",
"im",
",",
"hout",
"=",
"0.66",
",",
"is_offset",
"=",
"True",
",",
"is_clip",
"=",
"True",
",",
"is_random",
"=",
"False",
")",
":",
"hsv",
"=",
"rgb_to_hsv",
"(",
"im",
")",
"if",
"is_random",
":",
"hout",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"hout",
",",
"hout",
")",
"if",
"is_offset",
":",
"hsv",
"[",
"...",
",",
"0",
"]",
"+=",
"hout",
"else",
":",
"hsv",
"[",
"...",
",",
"0",
"]",
"=",
"hout",
"if",
"is_clip",
":",
"hsv",
"[",
"...",
",",
"0",
"]",
"=",
"np",
".",
"clip",
"(",
"hsv",
"[",
"...",
",",
"0",
"]",
",",
"0",
",",
"np",
".",
"inf",
")",
"# Hao : can remove green dots",
"rgb",
"=",
"hsv_to_rgb",
"(",
"hsv",
")",
"return",
"rgb"
] | Adjust hue of an RGB image.
This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type.
For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.and `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.
Parameters
-----------
im : numpy.array
An image with values between 0 and 255.
hout : float
The scale value for adjusting hue.
- If is_offset is False, set all hue values to this value. 0 is red; 0.33 is green; 0.66 is blue.
- If is_offset is True, add this value as the offset to the hue channel.
is_offset : boolean
Whether `hout` is added on HSV as offset or not. Default is True.
is_clip : boolean
If HSV value smaller than 0, set to 0. Default is True.
is_random : boolean
If True, randomly change hue. Default is False.
Returns
-------
numpy.array
A processed image.
Examples
---------
Random, add a random value between -0.2 and 0.2 as the offset to every hue values.
>>> im_hue = tl.prepro.adjust_hue(image, hout=0.2, is_offset=True, is_random=False)
Non-random, make all hue to green.
>>> im_green = tl.prepro.adjust_hue(image, hout=0.66, is_offset=False, is_random=False)
References
-----------
- `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__.
- `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.
- `StackOverflow: Changing image hue with python PIL <https://stackoverflow.com/questions/7274221/changing-image-hue-with-python-pil>`__. | [
"Adjust",
"hue",
"of",
"an",
"RGB",
"image",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1752-L1808 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | imresize | def imresize(x, size=None, interp='bicubic', mode=None):
"""Resize an image by given output size and method.
Warning, this function will rescale the value to [0, 255].
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
size : list of 2 int or None
For height and width.
interp : str
Interpolation method for re-sizing (`nearest`, `lanczos`, `bilinear`, `bicubic` (default) or `cubic`).
mode : str
The PIL image mode (`P`, `L`, etc.) to convert image before resizing.
Returns
-------
numpy.array
A processed image.
References
------------
- `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`__
"""
if size is None:
size = [100, 100]
if x.shape[-1] == 1:
# greyscale
x = scipy.misc.imresize(x[:, :, 0], size, interp=interp, mode=mode)
return x[:, :, np.newaxis]
else:
# rgb, bgr, rgba
return scipy.misc.imresize(x, size, interp=interp, mode=mode) | python | def imresize(x, size=None, interp='bicubic', mode=None):
"""Resize an image by given output size and method.
Warning, this function will rescale the value to [0, 255].
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
size : list of 2 int or None
For height and width.
interp : str
Interpolation method for re-sizing (`nearest`, `lanczos`, `bilinear`, `bicubic` (default) or `cubic`).
mode : str
The PIL image mode (`P`, `L`, etc.) to convert image before resizing.
Returns
-------
numpy.array
A processed image.
References
------------
- `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`__
"""
if size is None:
size = [100, 100]
if x.shape[-1] == 1:
# greyscale
x = scipy.misc.imresize(x[:, :, 0], size, interp=interp, mode=mode)
return x[:, :, np.newaxis]
else:
# rgb, bgr, rgba
return scipy.misc.imresize(x, size, interp=interp, mode=mode) | [
"def",
"imresize",
"(",
"x",
",",
"size",
"=",
"None",
",",
"interp",
"=",
"'bicubic'",
",",
"mode",
"=",
"None",
")",
":",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"[",
"100",
",",
"100",
"]",
"if",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"# greyscale",
"x",
"=",
"scipy",
".",
"misc",
".",
"imresize",
"(",
"x",
"[",
":",
",",
":",
",",
"0",
"]",
",",
"size",
",",
"interp",
"=",
"interp",
",",
"mode",
"=",
"mode",
")",
"return",
"x",
"[",
":",
",",
":",
",",
"np",
".",
"newaxis",
"]",
"else",
":",
"# rgb, bgr, rgba",
"return",
"scipy",
".",
"misc",
".",
"imresize",
"(",
"x",
",",
"size",
",",
"interp",
"=",
"interp",
",",
"mode",
"=",
"mode",
")"
] | Resize an image by given output size and method.
Warning, this function will rescale the value to [0, 255].
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
size : list of 2 int or None
For height and width.
interp : str
Interpolation method for re-sizing (`nearest`, `lanczos`, `bilinear`, `bicubic` (default) or `cubic`).
mode : str
The PIL image mode (`P`, `L`, etc.) to convert image before resizing.
Returns
-------
numpy.array
A processed image.
References
------------
- `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`__ | [
"Resize",
"an",
"image",
"by",
"given",
"output",
"size",
"and",
"method",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1822-L1857 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | pixel_value_scale | def pixel_value_scale(im, val=0.9, clip=None, is_random=False):
"""Scales each value in the pixels of the image.
Parameters
-----------
im : numpy.array
An image.
val : float
The scale value for changing pixel value.
- If is_random=False, multiply this value with all pixels.
- If is_random=True, multiply a value between [1-val, 1+val] with all pixels.
clip : tuple of 2 numbers
The minimum and maximum value.
is_random : boolean
If True, see ``val``.
Returns
-------
numpy.array
A processed image.
Examples
----------
Random
>>> im = pixel_value_scale(im, 0.1, [0, 255], is_random=True)
Non-random
>>> im = pixel_value_scale(im, 0.9, [0, 255], is_random=False)
"""
clip = clip if clip is not None else (-np.inf, np.inf)
if is_random:
scale = 1 + np.random.uniform(-val, val)
im = im * scale
else:
im = im * val
if len(clip) == 2:
im = np.clip(im, clip[0], clip[1])
else:
raise Exception("clip : tuple of 2 numbers")
return im | python | def pixel_value_scale(im, val=0.9, clip=None, is_random=False):
"""Scales each value in the pixels of the image.
Parameters
-----------
im : numpy.array
An image.
val : float
The scale value for changing pixel value.
- If is_random=False, multiply this value with all pixels.
- If is_random=True, multiply a value between [1-val, 1+val] with all pixels.
clip : tuple of 2 numbers
The minimum and maximum value.
is_random : boolean
If True, see ``val``.
Returns
-------
numpy.array
A processed image.
Examples
----------
Random
>>> im = pixel_value_scale(im, 0.1, [0, 255], is_random=True)
Non-random
>>> im = pixel_value_scale(im, 0.9, [0, 255], is_random=False)
"""
clip = clip if clip is not None else (-np.inf, np.inf)
if is_random:
scale = 1 + np.random.uniform(-val, val)
im = im * scale
else:
im = im * val
if len(clip) == 2:
im = np.clip(im, clip[0], clip[1])
else:
raise Exception("clip : tuple of 2 numbers")
return im | [
"def",
"pixel_value_scale",
"(",
"im",
",",
"val",
"=",
"0.9",
",",
"clip",
"=",
"None",
",",
"is_random",
"=",
"False",
")",
":",
"clip",
"=",
"clip",
"if",
"clip",
"is",
"not",
"None",
"else",
"(",
"-",
"np",
".",
"inf",
",",
"np",
".",
"inf",
")",
"if",
"is_random",
":",
"scale",
"=",
"1",
"+",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"val",
",",
"val",
")",
"im",
"=",
"im",
"*",
"scale",
"else",
":",
"im",
"=",
"im",
"*",
"val",
"if",
"len",
"(",
"clip",
")",
"==",
"2",
":",
"im",
"=",
"np",
".",
"clip",
"(",
"im",
",",
"clip",
"[",
"0",
"]",
",",
"clip",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"clip : tuple of 2 numbers\"",
")",
"return",
"im"
] | Scales each value in the pixels of the image.
Parameters
-----------
im : numpy.array
An image.
val : float
The scale value for changing pixel value.
- If is_random=False, multiply this value with all pixels.
- If is_random=True, multiply a value between [1-val, 1+val] with all pixels.
clip : tuple of 2 numbers
The minimum and maximum value.
is_random : boolean
If True, see ``val``.
Returns
-------
numpy.array
A processed image.
Examples
----------
Random
>>> im = pixel_value_scale(im, 0.1, [0, 255], is_random=True)
Non-random
>>> im = pixel_value_scale(im, 0.9, [0, 255], is_random=False) | [
"Scales",
"each",
"value",
"in",
"the",
"pixels",
"of",
"the",
"image",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1861-L1907 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | samplewise_norm | def samplewise_norm(
x, rescale=None, samplewise_center=False, samplewise_std_normalization=False, channel_index=2, epsilon=1e-7
):
"""Normalize an image by rescale, samplewise centering and samplewise centering in order.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
rescale : float
Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (before applying any other transformation)
samplewise_center : boolean
If True, set each sample mean to 0.
samplewise_std_normalization : boolean
If True, divide each input by its std.
epsilon : float
A small position value for dividing standard deviation.
Returns
-------
numpy.array
A processed image.
Examples
--------
>>> x = samplewise_norm(x, samplewise_center=True, samplewise_std_normalization=True)
>>> print(x.shape, np.mean(x), np.std(x))
(160, 176, 1), 0.0, 1.0
Notes
------
When samplewise_center and samplewise_std_normalization are True.
- For greyscale image, every pixels are subtracted and divided by the mean and std of whole image.
- For RGB image, every pixels are subtracted and divided by the mean and std of this pixel i.e. the mean and std of a pixel is 0 and 1.
"""
if rescale:
x *= rescale
if x.shape[channel_index] == 1:
# greyscale
if samplewise_center:
x = x - np.mean(x)
if samplewise_std_normalization:
x = x / np.std(x)
return x
elif x.shape[channel_index] == 3:
# rgb
if samplewise_center:
x = x - np.mean(x, axis=channel_index, keepdims=True)
if samplewise_std_normalization:
x = x / (np.std(x, axis=channel_index, keepdims=True) + epsilon)
return x
else:
raise Exception("Unsupported channels %d" % x.shape[channel_index]) | python | def samplewise_norm(
x, rescale=None, samplewise_center=False, samplewise_std_normalization=False, channel_index=2, epsilon=1e-7
):
"""Normalize an image by rescale, samplewise centering and samplewise centering in order.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
rescale : float
Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (before applying any other transformation)
samplewise_center : boolean
If True, set each sample mean to 0.
samplewise_std_normalization : boolean
If True, divide each input by its std.
epsilon : float
A small position value for dividing standard deviation.
Returns
-------
numpy.array
A processed image.
Examples
--------
>>> x = samplewise_norm(x, samplewise_center=True, samplewise_std_normalization=True)
>>> print(x.shape, np.mean(x), np.std(x))
(160, 176, 1), 0.0, 1.0
Notes
------
When samplewise_center and samplewise_std_normalization are True.
- For greyscale image, every pixels are subtracted and divided by the mean and std of whole image.
- For RGB image, every pixels are subtracted and divided by the mean and std of this pixel i.e. the mean and std of a pixel is 0 and 1.
"""
if rescale:
x *= rescale
if x.shape[channel_index] == 1:
# greyscale
if samplewise_center:
x = x - np.mean(x)
if samplewise_std_normalization:
x = x / np.std(x)
return x
elif x.shape[channel_index] == 3:
# rgb
if samplewise_center:
x = x - np.mean(x, axis=channel_index, keepdims=True)
if samplewise_std_normalization:
x = x / (np.std(x, axis=channel_index, keepdims=True) + epsilon)
return x
else:
raise Exception("Unsupported channels %d" % x.shape[channel_index]) | [
"def",
"samplewise_norm",
"(",
"x",
",",
"rescale",
"=",
"None",
",",
"samplewise_center",
"=",
"False",
",",
"samplewise_std_normalization",
"=",
"False",
",",
"channel_index",
"=",
"2",
",",
"epsilon",
"=",
"1e-7",
")",
":",
"if",
"rescale",
":",
"x",
"*=",
"rescale",
"if",
"x",
".",
"shape",
"[",
"channel_index",
"]",
"==",
"1",
":",
"# greyscale",
"if",
"samplewise_center",
":",
"x",
"=",
"x",
"-",
"np",
".",
"mean",
"(",
"x",
")",
"if",
"samplewise_std_normalization",
":",
"x",
"=",
"x",
"/",
"np",
".",
"std",
"(",
"x",
")",
"return",
"x",
"elif",
"x",
".",
"shape",
"[",
"channel_index",
"]",
"==",
"3",
":",
"# rgb",
"if",
"samplewise_center",
":",
"x",
"=",
"x",
"-",
"np",
".",
"mean",
"(",
"x",
",",
"axis",
"=",
"channel_index",
",",
"keepdims",
"=",
"True",
")",
"if",
"samplewise_std_normalization",
":",
"x",
"=",
"x",
"/",
"(",
"np",
".",
"std",
"(",
"x",
",",
"axis",
"=",
"channel_index",
",",
"keepdims",
"=",
"True",
")",
"+",
"epsilon",
")",
"return",
"x",
"else",
":",
"raise",
"Exception",
"(",
"\"Unsupported channels %d\"",
"%",
"x",
".",
"shape",
"[",
"channel_index",
"]",
")"
] | Normalize an image by rescale, samplewise centering and samplewise centering in order.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
rescale : float
Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (before applying any other transformation)
samplewise_center : boolean
If True, set each sample mean to 0.
samplewise_std_normalization : boolean
If True, divide each input by its std.
epsilon : float
A small position value for dividing standard deviation.
Returns
-------
numpy.array
A processed image.
Examples
--------
>>> x = samplewise_norm(x, samplewise_center=True, samplewise_std_normalization=True)
>>> print(x.shape, np.mean(x), np.std(x))
(160, 176, 1), 0.0, 1.0
Notes
------
When samplewise_center and samplewise_std_normalization are True.
- For greyscale image, every pixels are subtracted and divided by the mean and std of whole image.
- For RGB image, every pixels are subtracted and divided by the mean and std of this pixel i.e. the mean and std of a pixel is 0 and 1. | [
"Normalize",
"an",
"image",
"by",
"rescale",
"samplewise",
"centering",
"and",
"samplewise",
"centering",
"in",
"order",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1911-L1965 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | featurewise_norm | def featurewise_norm(x, mean=None, std=None, epsilon=1e-7):
"""Normalize every pixels by the same given mean and std, which are usually
compute from all examples.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
mean : float
Value for subtraction.
std : float
Value for division.
epsilon : float
A small position value for dividing standard deviation.
Returns
-------
numpy.array
A processed image.
"""
if mean:
x = x - mean
if std:
x = x / (std + epsilon)
return x | python | def featurewise_norm(x, mean=None, std=None, epsilon=1e-7):
"""Normalize every pixels by the same given mean and std, which are usually
compute from all examples.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
mean : float
Value for subtraction.
std : float
Value for division.
epsilon : float
A small position value for dividing standard deviation.
Returns
-------
numpy.array
A processed image.
"""
if mean:
x = x - mean
if std:
x = x / (std + epsilon)
return x | [
"def",
"featurewise_norm",
"(",
"x",
",",
"mean",
"=",
"None",
",",
"std",
"=",
"None",
",",
"epsilon",
"=",
"1e-7",
")",
":",
"if",
"mean",
":",
"x",
"=",
"x",
"-",
"mean",
"if",
"std",
":",
"x",
"=",
"x",
"/",
"(",
"std",
"+",
"epsilon",
")",
"return",
"x"
] | Normalize every pixels by the same given mean and std, which are usually
compute from all examples.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
mean : float
Value for subtraction.
std : float
Value for division.
epsilon : float
A small position value for dividing standard deviation.
Returns
-------
numpy.array
A processed image. | [
"Normalize",
"every",
"pixels",
"by",
"the",
"same",
"given",
"mean",
"and",
"std",
"which",
"are",
"usually",
"compute",
"from",
"all",
"examples",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1968-L1993 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | get_zca_whitening_principal_components_img | def get_zca_whitening_principal_components_img(X):
"""Return the ZCA whitening principal components matrix.
Parameters
-----------
x : numpy.array
Batch of images with dimension of [n_example, row, col, channel] (default).
Returns
-------
numpy.array
A processed image.
"""
flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3]))
tl.logging.info("zca : computing sigma ..")
sigma = np.dot(flatX.T, flatX) / flatX.shape[0]
tl.logging.info("zca : computing U, S and V ..")
U, S, _ = linalg.svd(sigma) # USV
tl.logging.info("zca : computing principal components ..")
principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T)
return principal_components | python | def get_zca_whitening_principal_components_img(X):
"""Return the ZCA whitening principal components matrix.
Parameters
-----------
x : numpy.array
Batch of images with dimension of [n_example, row, col, channel] (default).
Returns
-------
numpy.array
A processed image.
"""
flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3]))
tl.logging.info("zca : computing sigma ..")
sigma = np.dot(flatX.T, flatX) / flatX.shape[0]
tl.logging.info("zca : computing U, S and V ..")
U, S, _ = linalg.svd(sigma) # USV
tl.logging.info("zca : computing principal components ..")
principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T)
return principal_components | [
"def",
"get_zca_whitening_principal_components_img",
"(",
"X",
")",
":",
"flatX",
"=",
"np",
".",
"reshape",
"(",
"X",
",",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"X",
".",
"shape",
"[",
"1",
"]",
"*",
"X",
".",
"shape",
"[",
"2",
"]",
"*",
"X",
".",
"shape",
"[",
"3",
"]",
")",
")",
"tl",
".",
"logging",
".",
"info",
"(",
"\"zca : computing sigma ..\"",
")",
"sigma",
"=",
"np",
".",
"dot",
"(",
"flatX",
".",
"T",
",",
"flatX",
")",
"/",
"flatX",
".",
"shape",
"[",
"0",
"]",
"tl",
".",
"logging",
".",
"info",
"(",
"\"zca : computing U, S and V ..\"",
")",
"U",
",",
"S",
",",
"_",
"=",
"linalg",
".",
"svd",
"(",
"sigma",
")",
"# USV",
"tl",
".",
"logging",
".",
"info",
"(",
"\"zca : computing principal components ..\"",
")",
"principal_components",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"U",
",",
"np",
".",
"diag",
"(",
"1.",
"/",
"np",
".",
"sqrt",
"(",
"S",
"+",
"10e-7",
")",
")",
")",
",",
"U",
".",
"T",
")",
"return",
"principal_components"
] | Return the ZCA whitening principal components matrix.
Parameters
-----------
x : numpy.array
Batch of images with dimension of [n_example, row, col, channel] (default).
Returns
-------
numpy.array
A processed image. | [
"Return",
"the",
"ZCA",
"whitening",
"principal",
"components",
"matrix",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L1997-L2018 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | zca_whitening | def zca_whitening(x, principal_components):
"""Apply ZCA whitening on an image by given principal components matrix.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
principal_components : matrix
Matrix from ``get_zca_whitening_principal_components_img``.
Returns
-------
numpy.array
A processed image.
"""
flatx = np.reshape(x, (x.size))
# tl.logging.info(principal_components.shape, x.shape) # ((28160, 28160), (160, 176, 1))
# flatx = np.reshape(x, (x.shape))
# flatx = np.reshape(x, (x.shape[0], ))
# tl.logging.info(flatx.shape) # (160, 176, 1)
whitex = np.dot(flatx, principal_components)
x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))
return x | python | def zca_whitening(x, principal_components):
"""Apply ZCA whitening on an image by given principal components matrix.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
principal_components : matrix
Matrix from ``get_zca_whitening_principal_components_img``.
Returns
-------
numpy.array
A processed image.
"""
flatx = np.reshape(x, (x.size))
# tl.logging.info(principal_components.shape, x.shape) # ((28160, 28160), (160, 176, 1))
# flatx = np.reshape(x, (x.shape))
# flatx = np.reshape(x, (x.shape[0], ))
# tl.logging.info(flatx.shape) # (160, 176, 1)
whitex = np.dot(flatx, principal_components)
x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2]))
return x | [
"def",
"zca_whitening",
"(",
"x",
",",
"principal_components",
")",
":",
"flatx",
"=",
"np",
".",
"reshape",
"(",
"x",
",",
"(",
"x",
".",
"size",
")",
")",
"# tl.logging.info(principal_components.shape, x.shape) # ((28160, 28160), (160, 176, 1))",
"# flatx = np.reshape(x, (x.shape))",
"# flatx = np.reshape(x, (x.shape[0], ))",
"# tl.logging.info(flatx.shape) # (160, 176, 1)",
"whitex",
"=",
"np",
".",
"dot",
"(",
"flatx",
",",
"principal_components",
")",
"x",
"=",
"np",
".",
"reshape",
"(",
"whitex",
",",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"x",
".",
"shape",
"[",
"1",
"]",
",",
"x",
".",
"shape",
"[",
"2",
"]",
")",
")",
"return",
"x"
] | Apply ZCA whitening on an image by given principal components matrix.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
principal_components : matrix
Matrix from ``get_zca_whitening_principal_components_img``.
Returns
-------
numpy.array
A processed image. | [
"Apply",
"ZCA",
"whitening",
"on",
"an",
"image",
"by",
"given",
"principal",
"components",
"matrix",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2021-L2044 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | channel_shift | def channel_shift(x, intensity, is_random=False, channel_index=2):
"""Shift the channels of an image, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
intensity : float
Intensity of shifting.
is_random : boolean
If True, randomly shift. Default is False.
channel_index : int
Index of channel. Default is 2.
Returns
-------
numpy.array
A processed image.
"""
if is_random:
factor = np.random.uniform(-intensity, intensity)
else:
factor = intensity
x = np.rollaxis(x, channel_index, 0)
min_x, max_x = np.min(x), np.max(x)
channel_images = [np.clip(x_channel + factor, min_x, max_x) for x_channel in x]
x = np.stack(channel_images, axis=0)
x = np.rollaxis(x, 0, channel_index + 1)
return x | python | def channel_shift(x, intensity, is_random=False, channel_index=2):
"""Shift the channels of an image, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
intensity : float
Intensity of shifting.
is_random : boolean
If True, randomly shift. Default is False.
channel_index : int
Index of channel. Default is 2.
Returns
-------
numpy.array
A processed image.
"""
if is_random:
factor = np.random.uniform(-intensity, intensity)
else:
factor = intensity
x = np.rollaxis(x, channel_index, 0)
min_x, max_x = np.min(x), np.max(x)
channel_images = [np.clip(x_channel + factor, min_x, max_x) for x_channel in x]
x = np.stack(channel_images, axis=0)
x = np.rollaxis(x, 0, channel_index + 1)
return x | [
"def",
"channel_shift",
"(",
"x",
",",
"intensity",
",",
"is_random",
"=",
"False",
",",
"channel_index",
"=",
"2",
")",
":",
"if",
"is_random",
":",
"factor",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"intensity",
",",
"intensity",
")",
"else",
":",
"factor",
"=",
"intensity",
"x",
"=",
"np",
".",
"rollaxis",
"(",
"x",
",",
"channel_index",
",",
"0",
")",
"min_x",
",",
"max_x",
"=",
"np",
".",
"min",
"(",
"x",
")",
",",
"np",
".",
"max",
"(",
"x",
")",
"channel_images",
"=",
"[",
"np",
".",
"clip",
"(",
"x_channel",
"+",
"factor",
",",
"min_x",
",",
"max_x",
")",
"for",
"x_channel",
"in",
"x",
"]",
"x",
"=",
"np",
".",
"stack",
"(",
"channel_images",
",",
"axis",
"=",
"0",
")",
"x",
"=",
"np",
".",
"rollaxis",
"(",
"x",
",",
"0",
",",
"channel_index",
"+",
"1",
")",
"return",
"x"
] | Shift the channels of an image, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
intensity : float
Intensity of shifting.
is_random : boolean
If True, randomly shift. Default is False.
channel_index : int
Index of channel. Default is 2.
Returns
-------
numpy.array
A processed image. | [
"Shift",
"the",
"channels",
"of",
"an",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"see",
"numpy",
".",
"rollaxis",
"<https",
":",
"//",
"docs",
".",
"scipy",
".",
"org",
"/",
"doc",
"/",
"numpy",
"/",
"reference",
"/",
"generated",
"/",
"numpy",
".",
"rollaxis",
".",
"html",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2060-L2089 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | channel_shift_multi | def channel_shift_multi(x, intensity, is_random=False, channel_index=2):
"""Shift the channels of images with the same arguments, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.channel_shift``.
Returns
-------
numpy.array
A list of processed images.
"""
if is_random:
factor = np.random.uniform(-intensity, intensity)
else:
factor = intensity
results = []
for data in x:
data = np.rollaxis(data, channel_index, 0)
min_x, max_x = np.min(data), np.max(data)
channel_images = [np.clip(x_channel + factor, min_x, max_x) for x_channel in x]
data = np.stack(channel_images, axis=0)
data = np.rollaxis(x, 0, channel_index + 1)
results.append(data)
return np.asarray(results) | python | def channel_shift_multi(x, intensity, is_random=False, channel_index=2):
"""Shift the channels of images with the same arguments, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.channel_shift``.
Returns
-------
numpy.array
A list of processed images.
"""
if is_random:
factor = np.random.uniform(-intensity, intensity)
else:
factor = intensity
results = []
for data in x:
data = np.rollaxis(data, channel_index, 0)
min_x, max_x = np.min(data), np.max(data)
channel_images = [np.clip(x_channel + factor, min_x, max_x) for x_channel in x]
data = np.stack(channel_images, axis=0)
data = np.rollaxis(x, 0, channel_index + 1)
results.append(data)
return np.asarray(results) | [
"def",
"channel_shift_multi",
"(",
"x",
",",
"intensity",
",",
"is_random",
"=",
"False",
",",
"channel_index",
"=",
"2",
")",
":",
"if",
"is_random",
":",
"factor",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"intensity",
",",
"intensity",
")",
"else",
":",
"factor",
"=",
"intensity",
"results",
"=",
"[",
"]",
"for",
"data",
"in",
"x",
":",
"data",
"=",
"np",
".",
"rollaxis",
"(",
"data",
",",
"channel_index",
",",
"0",
")",
"min_x",
",",
"max_x",
"=",
"np",
".",
"min",
"(",
"data",
")",
",",
"np",
".",
"max",
"(",
"data",
")",
"channel_images",
"=",
"[",
"np",
".",
"clip",
"(",
"x_channel",
"+",
"factor",
",",
"min_x",
",",
"max_x",
")",
"for",
"x_channel",
"in",
"x",
"]",
"data",
"=",
"np",
".",
"stack",
"(",
"channel_images",
",",
"axis",
"=",
"0",
")",
"data",
"=",
"np",
".",
"rollaxis",
"(",
"x",
",",
"0",
",",
"channel_index",
"+",
"1",
")",
"results",
".",
"append",
"(",
"data",
")",
"return",
"np",
".",
"asarray",
"(",
"results",
")"
] | Shift the channels of images with the same arguments, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy.array
List of images with dimension of [n_images, row, col, channel] (default).
others : args
See ``tl.prepro.channel_shift``.
Returns
-------
numpy.array
A list of processed images. | [
"Shift",
"the",
"channels",
"of",
"images",
"with",
"the",
"same",
"arguments",
"randomly",
"or",
"non",
"-",
"randomly",
"see",
"numpy",
".",
"rollaxis",
"<https",
":",
"//",
"docs",
".",
"scipy",
".",
"org",
"/",
"doc",
"/",
"numpy",
"/",
"reference",
"/",
"generated",
"/",
"numpy",
".",
"rollaxis",
".",
"html",
">",
"__",
".",
"Usually",
"be",
"used",
"for",
"image",
"segmentation",
"which",
"x",
"=",
"[",
"X",
"Y",
"]",
"X",
"and",
"Y",
"should",
"be",
"matched",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2099-L2129 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | drop | def drop(x, keep=0.5):
"""Randomly set some pixels to zero by a given keeping probability.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] or [row, col].
keep : float
The keeping probability (0, 1), the lower more values will be set to zero.
Returns
-------
numpy.array
A processed image.
"""
if len(x.shape) == 3:
if x.shape[-1] == 3: # color
img_size = x.shape
mask = np.random.binomial(n=1, p=keep, size=x.shape[:-1])
for i in range(3):
x[:, :, i] = np.multiply(x[:, :, i], mask)
elif x.shape[-1] == 1: # greyscale image
img_size = x.shape
x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size))
else:
raise Exception("Unsupported shape {}".format(x.shape))
elif len(x.shape) == 2 or 1: # greyscale matrix (image) or vector
img_size = x.shape
x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size))
else:
raise Exception("Unsupported shape {}".format(x.shape))
return x | python | def drop(x, keep=0.5):
"""Randomly set some pixels to zero by a given keeping probability.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] or [row, col].
keep : float
The keeping probability (0, 1), the lower more values will be set to zero.
Returns
-------
numpy.array
A processed image.
"""
if len(x.shape) == 3:
if x.shape[-1] == 3: # color
img_size = x.shape
mask = np.random.binomial(n=1, p=keep, size=x.shape[:-1])
for i in range(3):
x[:, :, i] = np.multiply(x[:, :, i], mask)
elif x.shape[-1] == 1: # greyscale image
img_size = x.shape
x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size))
else:
raise Exception("Unsupported shape {}".format(x.shape))
elif len(x.shape) == 2 or 1: # greyscale matrix (image) or vector
img_size = x.shape
x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size))
else:
raise Exception("Unsupported shape {}".format(x.shape))
return x | [
"def",
"drop",
"(",
"x",
",",
"keep",
"=",
"0.5",
")",
":",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"3",
":",
"if",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"3",
":",
"# color",
"img_size",
"=",
"x",
".",
"shape",
"mask",
"=",
"np",
".",
"random",
".",
"binomial",
"(",
"n",
"=",
"1",
",",
"p",
"=",
"keep",
",",
"size",
"=",
"x",
".",
"shape",
"[",
":",
"-",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"x",
"[",
":",
",",
":",
",",
"i",
"]",
"=",
"np",
".",
"multiply",
"(",
"x",
"[",
":",
",",
":",
",",
"i",
"]",
",",
"mask",
")",
"elif",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"# greyscale image",
"img_size",
"=",
"x",
".",
"shape",
"x",
"=",
"np",
".",
"multiply",
"(",
"x",
",",
"np",
".",
"random",
".",
"binomial",
"(",
"n",
"=",
"1",
",",
"p",
"=",
"keep",
",",
"size",
"=",
"img_size",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Unsupported shape {}\"",
".",
"format",
"(",
"x",
".",
"shape",
")",
")",
"elif",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"2",
"or",
"1",
":",
"# greyscale matrix (image) or vector",
"img_size",
"=",
"x",
".",
"shape",
"x",
"=",
"np",
".",
"multiply",
"(",
"x",
",",
"np",
".",
"random",
".",
"binomial",
"(",
"n",
"=",
"1",
",",
"p",
"=",
"keep",
",",
"size",
"=",
"img_size",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Unsupported shape {}\"",
".",
"format",
"(",
"x",
".",
"shape",
")",
")",
"return",
"x"
] | Randomly set some pixels to zero by a given keeping probability.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] or [row, col].
keep : float
The keeping probability (0, 1), the lower more values will be set to zero.
Returns
-------
numpy.array
A processed image. | [
"Randomly",
"set",
"some",
"pixels",
"to",
"zero",
"by",
"a",
"given",
"keeping",
"probability",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2133-L2165 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | array_to_img | def array_to_img(x, dim_ordering=(0, 1, 2), scale=True):
"""Converts a numpy array to PIL image object (uint8 format).
Parameters
----------
x : numpy.array
An image with dimension of 3 and channels of 1 or 3.
dim_ordering : tuple of 3 int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
scale : boolean
If True, converts image to [0, 255] from any range of value like [-1, 2]. Default is True.
Returns
-------
PIL.image
An image.
References
-----------
`PIL Image.fromarray <http://pillow.readthedocs.io/en/3.1.x/reference/Image.html?highlight=fromarray>`__
"""
# if dim_ordering == 'default':
# dim_ordering = K.image_dim_ordering()
# if dim_ordering == 'th': # theano
# x = x.transpose(1, 2, 0)
x = x.transpose(dim_ordering)
if scale:
x += max(-np.min(x), 0)
x_max = np.max(x)
if x_max != 0:
# tl.logging.info(x_max)
# x /= x_max
x = x / x_max
x *= 255
if x.shape[2] == 3:
# RGB
return PIL.Image.fromarray(x.astype('uint8'), 'RGB')
elif x.shape[2] == 1:
# grayscale
return PIL.Image.fromarray(x[:, :, 0].astype('uint8'), 'L')
else:
raise Exception('Unsupported channel number: ', x.shape[2]) | python | def array_to_img(x, dim_ordering=(0, 1, 2), scale=True):
"""Converts a numpy array to PIL image object (uint8 format).
Parameters
----------
x : numpy.array
An image with dimension of 3 and channels of 1 or 3.
dim_ordering : tuple of 3 int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
scale : boolean
If True, converts image to [0, 255] from any range of value like [-1, 2]. Default is True.
Returns
-------
PIL.image
An image.
References
-----------
`PIL Image.fromarray <http://pillow.readthedocs.io/en/3.1.x/reference/Image.html?highlight=fromarray>`__
"""
# if dim_ordering == 'default':
# dim_ordering = K.image_dim_ordering()
# if dim_ordering == 'th': # theano
# x = x.transpose(1, 2, 0)
x = x.transpose(dim_ordering)
if scale:
x += max(-np.min(x), 0)
x_max = np.max(x)
if x_max != 0:
# tl.logging.info(x_max)
# x /= x_max
x = x / x_max
x *= 255
if x.shape[2] == 3:
# RGB
return PIL.Image.fromarray(x.astype('uint8'), 'RGB')
elif x.shape[2] == 1:
# grayscale
return PIL.Image.fromarray(x[:, :, 0].astype('uint8'), 'L')
else:
raise Exception('Unsupported channel number: ', x.shape[2]) | [
"def",
"array_to_img",
"(",
"x",
",",
"dim_ordering",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
",",
"scale",
"=",
"True",
")",
":",
"# if dim_ordering == 'default':",
"# dim_ordering = K.image_dim_ordering()",
"# if dim_ordering == 'th': # theano",
"# x = x.transpose(1, 2, 0)",
"x",
"=",
"x",
".",
"transpose",
"(",
"dim_ordering",
")",
"if",
"scale",
":",
"x",
"+=",
"max",
"(",
"-",
"np",
".",
"min",
"(",
"x",
")",
",",
"0",
")",
"x_max",
"=",
"np",
".",
"max",
"(",
"x",
")",
"if",
"x_max",
"!=",
"0",
":",
"# tl.logging.info(x_max)",
"# x /= x_max",
"x",
"=",
"x",
"/",
"x_max",
"x",
"*=",
"255",
"if",
"x",
".",
"shape",
"[",
"2",
"]",
"==",
"3",
":",
"# RGB",
"return",
"PIL",
".",
"Image",
".",
"fromarray",
"(",
"x",
".",
"astype",
"(",
"'uint8'",
")",
",",
"'RGB'",
")",
"elif",
"x",
".",
"shape",
"[",
"2",
"]",
"==",
"1",
":",
"# grayscale",
"return",
"PIL",
".",
"Image",
".",
"fromarray",
"(",
"x",
"[",
":",
",",
":",
",",
"0",
"]",
".",
"astype",
"(",
"'uint8'",
")",
",",
"'L'",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Unsupported channel number: '",
",",
"x",
".",
"shape",
"[",
"2",
"]",
")"
] | Converts a numpy array to PIL image object (uint8 format).
Parameters
----------
x : numpy.array
An image with dimension of 3 and channels of 1 or 3.
dim_ordering : tuple of 3 int
Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0).
scale : boolean
If True, converts image to [0, 255] from any range of value like [-1, 2]. Default is True.
Returns
-------
PIL.image
An image.
References
-----------
`PIL Image.fromarray <http://pillow.readthedocs.io/en/3.1.x/reference/Image.html?highlight=fromarray>`__ | [
"Converts",
"a",
"numpy",
"array",
"to",
"PIL",
"image",
"object",
"(",
"uint8",
"format",
")",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2180-L2227 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | find_contours | def find_contours(x, level=0.8, fully_connected='low', positive_orientation='low'):
"""Find iso-valued contours in a 2D array for a given level value, returns list of (n, 2)-ndarrays
see `skimage.measure.find_contours <http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours>`__.
Parameters
------------
x : 2D ndarray of double.
Input data in which to find contours.
level : float
Value along which to find contours in the array.
fully_connected : str
Either `low` or `high`. Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.)
positive_orientation : str
Either `low` or `high`. Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If `low` then contours will wind counter-clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour.
Returns
--------
list of (n,2)-ndarrays
Each contour is an ndarray of shape (n, 2), consisting of n (row, column) coordinates along the contour.
"""
return skimage.measure.find_contours(
x, level, fully_connected=fully_connected, positive_orientation=positive_orientation
) | python | def find_contours(x, level=0.8, fully_connected='low', positive_orientation='low'):
"""Find iso-valued contours in a 2D array for a given level value, returns list of (n, 2)-ndarrays
see `skimage.measure.find_contours <http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours>`__.
Parameters
------------
x : 2D ndarray of double.
Input data in which to find contours.
level : float
Value along which to find contours in the array.
fully_connected : str
Either `low` or `high`. Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.)
positive_orientation : str
Either `low` or `high`. Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If `low` then contours will wind counter-clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour.
Returns
--------
list of (n,2)-ndarrays
Each contour is an ndarray of shape (n, 2), consisting of n (row, column) coordinates along the contour.
"""
return skimage.measure.find_contours(
x, level, fully_connected=fully_connected, positive_orientation=positive_orientation
) | [
"def",
"find_contours",
"(",
"x",
",",
"level",
"=",
"0.8",
",",
"fully_connected",
"=",
"'low'",
",",
"positive_orientation",
"=",
"'low'",
")",
":",
"return",
"skimage",
".",
"measure",
".",
"find_contours",
"(",
"x",
",",
"level",
",",
"fully_connected",
"=",
"fully_connected",
",",
"positive_orientation",
"=",
"positive_orientation",
")"
] | Find iso-valued contours in a 2D array for a given level value, returns list of (n, 2)-ndarrays
see `skimage.measure.find_contours <http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours>`__.
Parameters
------------
x : 2D ndarray of double.
Input data in which to find contours.
level : float
Value along which to find contours in the array.
fully_connected : str
Either `low` or `high`. Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.)
positive_orientation : str
Either `low` or `high`. Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If `low` then contours will wind counter-clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour.
Returns
--------
list of (n,2)-ndarrays
Each contour is an ndarray of shape (n, 2), consisting of n (row, column) coordinates along the contour. | [
"Find",
"iso",
"-",
"valued",
"contours",
"in",
"a",
"2D",
"array",
"for",
"a",
"given",
"level",
"value",
"returns",
"list",
"of",
"(",
"n",
"2",
")",
"-",
"ndarrays",
"see",
"skimage",
".",
"measure",
".",
"find_contours",
"<http",
":",
"//",
"scikit",
"-",
"image",
".",
"org",
"/",
"docs",
"/",
"dev",
"/",
"api",
"/",
"skimage",
".",
"measure",
".",
"html#skimage",
".",
"measure",
".",
"find_contours",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2230-L2253 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | pt2map | def pt2map(list_points=None, size=(100, 100), val=1):
"""Inputs a list of points, return a 2D image.
Parameters
--------------
list_points : list of 2 int
[[x, y], [x, y]..] for point coordinates.
size : tuple of 2 int
(w, h) for output size.
val : float or int
For the contour value.
Returns
-------
numpy.array
An image.
"""
if list_points is None:
raise Exception("list_points : list of 2 int")
i_m = np.zeros(size)
if len(list_points) == 0:
return i_m
for xx in list_points:
for x in xx:
# tl.logging.info(x)
i_m[int(np.round(x[0]))][int(np.round(x[1]))] = val
return i_m | python | def pt2map(list_points=None, size=(100, 100), val=1):
"""Inputs a list of points, return a 2D image.
Parameters
--------------
list_points : list of 2 int
[[x, y], [x, y]..] for point coordinates.
size : tuple of 2 int
(w, h) for output size.
val : float or int
For the contour value.
Returns
-------
numpy.array
An image.
"""
if list_points is None:
raise Exception("list_points : list of 2 int")
i_m = np.zeros(size)
if len(list_points) == 0:
return i_m
for xx in list_points:
for x in xx:
# tl.logging.info(x)
i_m[int(np.round(x[0]))][int(np.round(x[1]))] = val
return i_m | [
"def",
"pt2map",
"(",
"list_points",
"=",
"None",
",",
"size",
"=",
"(",
"100",
",",
"100",
")",
",",
"val",
"=",
"1",
")",
":",
"if",
"list_points",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"list_points : list of 2 int\"",
")",
"i_m",
"=",
"np",
".",
"zeros",
"(",
"size",
")",
"if",
"len",
"(",
"list_points",
")",
"==",
"0",
":",
"return",
"i_m",
"for",
"xx",
"in",
"list_points",
":",
"for",
"x",
"in",
"xx",
":",
"# tl.logging.info(x)",
"i_m",
"[",
"int",
"(",
"np",
".",
"round",
"(",
"x",
"[",
"0",
"]",
")",
")",
"]",
"[",
"int",
"(",
"np",
".",
"round",
"(",
"x",
"[",
"1",
"]",
")",
")",
"]",
"=",
"val",
"return",
"i_m"
] | Inputs a list of points, return a 2D image.
Parameters
--------------
list_points : list of 2 int
[[x, y], [x, y]..] for point coordinates.
size : tuple of 2 int
(w, h) for output size.
val : float or int
For the contour value.
Returns
-------
numpy.array
An image. | [
"Inputs",
"a",
"list",
"of",
"points",
"return",
"a",
"2D",
"image",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2256-L2283 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | binary_dilation | def binary_dilation(x, radius=3):
"""Return fast binary morphological dilation of an image.
see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__.
Parameters
-----------
x : 2D array
A binary image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed binary image.
"""
mask = disk(radius)
x = _binary_dilation(x, selem=mask)
return x | python | def binary_dilation(x, radius=3):
"""Return fast binary morphological dilation of an image.
see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__.
Parameters
-----------
x : 2D array
A binary image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed binary image.
"""
mask = disk(radius)
x = _binary_dilation(x, selem=mask)
return x | [
"def",
"binary_dilation",
"(",
"x",
",",
"radius",
"=",
"3",
")",
":",
"mask",
"=",
"disk",
"(",
"radius",
")",
"x",
"=",
"_binary_dilation",
"(",
"x",
",",
"selem",
"=",
"mask",
")",
"return",
"x"
] | Return fast binary morphological dilation of an image.
see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__.
Parameters
-----------
x : 2D array
A binary image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed binary image. | [
"Return",
"fast",
"binary",
"morphological",
"dilation",
"of",
"an",
"image",
".",
"see",
"skimage",
".",
"morphology",
".",
"binary_dilation",
"<http",
":",
"//",
"scikit",
"-",
"image",
".",
"org",
"/",
"docs",
"/",
"dev",
"/",
"api",
"/",
"skimage",
".",
"morphology",
".",
"html#skimage",
".",
"morphology",
".",
"binary_dilation",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2286-L2306 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | dilation | def dilation(x, radius=3):
"""Return greyscale morphological dilation of an image,
see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`__.
Parameters
-----------
x : 2D array
An greyscale image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed greyscale image.
"""
mask = disk(radius)
x = dilation(x, selem=mask)
return x | python | def dilation(x, radius=3):
"""Return greyscale morphological dilation of an image,
see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`__.
Parameters
-----------
x : 2D array
An greyscale image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed greyscale image.
"""
mask = disk(radius)
x = dilation(x, selem=mask)
return x | [
"def",
"dilation",
"(",
"x",
",",
"radius",
"=",
"3",
")",
":",
"mask",
"=",
"disk",
"(",
"radius",
")",
"x",
"=",
"dilation",
"(",
"x",
",",
"selem",
"=",
"mask",
")",
"return",
"x"
] | Return greyscale morphological dilation of an image,
see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`__.
Parameters
-----------
x : 2D array
An greyscale image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed greyscale image. | [
"Return",
"greyscale",
"morphological",
"dilation",
"of",
"an",
"image",
"see",
"skimage",
".",
"morphology",
".",
"dilation",
"<http",
":",
"//",
"scikit",
"-",
"image",
".",
"org",
"/",
"docs",
"/",
"dev",
"/",
"api",
"/",
"skimage",
".",
"morphology",
".",
"html#skimage",
".",
"morphology",
".",
"dilation",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2309-L2329 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | binary_erosion | def binary_erosion(x, radius=3):
"""Return binary morphological erosion of an image,
see `skimage.morphology.binary_erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_erosion>`__.
Parameters
-----------
x : 2D array
A binary image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed binary image.
"""
mask = disk(radius)
x = _binary_erosion(x, selem=mask)
return x | python | def binary_erosion(x, radius=3):
"""Return binary morphological erosion of an image,
see `skimage.morphology.binary_erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_erosion>`__.
Parameters
-----------
x : 2D array
A binary image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed binary image.
"""
mask = disk(radius)
x = _binary_erosion(x, selem=mask)
return x | [
"def",
"binary_erosion",
"(",
"x",
",",
"radius",
"=",
"3",
")",
":",
"mask",
"=",
"disk",
"(",
"radius",
")",
"x",
"=",
"_binary_erosion",
"(",
"x",
",",
"selem",
"=",
"mask",
")",
"return",
"x"
] | Return binary morphological erosion of an image,
see `skimage.morphology.binary_erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_erosion>`__.
Parameters
-----------
x : 2D array
A binary image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed binary image. | [
"Return",
"binary",
"morphological",
"erosion",
"of",
"an",
"image",
"see",
"skimage",
".",
"morphology",
".",
"binary_erosion",
"<http",
":",
"//",
"scikit",
"-",
"image",
".",
"org",
"/",
"docs",
"/",
"dev",
"/",
"api",
"/",
"skimage",
".",
"morphology",
".",
"html#skimage",
".",
"morphology",
".",
"binary_erosion",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2332-L2351 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | erosion | def erosion(x, radius=3):
"""Return greyscale morphological erosion of an image,
see `skimage.morphology.erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.erosion>`__.
Parameters
-----------
x : 2D array
A greyscale image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed greyscale image.
"""
mask = disk(radius)
x = _erosion(x, selem=mask)
return x | python | def erosion(x, radius=3):
"""Return greyscale morphological erosion of an image,
see `skimage.morphology.erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.erosion>`__.
Parameters
-----------
x : 2D array
A greyscale image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed greyscale image.
"""
mask = disk(radius)
x = _erosion(x, selem=mask)
return x | [
"def",
"erosion",
"(",
"x",
",",
"radius",
"=",
"3",
")",
":",
"mask",
"=",
"disk",
"(",
"radius",
")",
"x",
"=",
"_erosion",
"(",
"x",
",",
"selem",
"=",
"mask",
")",
"return",
"x"
] | Return greyscale morphological erosion of an image,
see `skimage.morphology.erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.erosion>`__.
Parameters
-----------
x : 2D array
A greyscale image.
radius : int
For the radius of mask.
Returns
-------
numpy.array
A processed greyscale image. | [
"Return",
"greyscale",
"morphological",
"erosion",
"of",
"an",
"image",
"see",
"skimage",
".",
"morphology",
".",
"erosion",
"<http",
":",
"//",
"scikit",
"-",
"image",
".",
"org",
"/",
"docs",
"/",
"dev",
"/",
"api",
"/",
"skimage",
".",
"morphology",
".",
"html#skimage",
".",
"morphology",
".",
"erosion",
">",
"__",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2354-L2373 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_coords_rescale | def obj_box_coords_rescale(coords=None, shape=None):
"""Scale down a list of coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1].
Parameters
------------
coords : list of list of 4 ints or None
For coordinates of more than one images .e.g.[[x, y, w, h], [x, y, w, h], ...].
shape : list of 2 int or None
【height, width].
Returns
-------
list of list of 4 numbers
A list of new bounding boxes.
Examples
---------
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50], [10, 10, 20, 20]], shape=[100, 100])
>>> print(coords)
[[0.3, 0.4, 0.5, 0.5], [0.1, 0.1, 0.2, 0.2]]
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[50, 100])
>>> print(coords)
[[0.3, 0.8, 0.5, 1.0]]
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[100, 200])
>>> print(coords)
[[0.15, 0.4, 0.25, 0.5]]
Returns
-------
list of 4 numbers
New coordinates.
"""
if coords is None:
coords = []
if shape is None:
shape = [100, 200]
imh, imw = shape[0], shape[1]
imh = imh * 1.0 # * 1.0 for python2 : force division to be float point
imw = imw * 1.0
coords_new = list()
for coord in coords:
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
x = coord[0] / imw
y = coord[1] / imh
w = coord[2] / imw
h = coord[3] / imh
coords_new.append([x, y, w, h])
return coords_new | python | def obj_box_coords_rescale(coords=None, shape=None):
"""Scale down a list of coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1].
Parameters
------------
coords : list of list of 4 ints or None
For coordinates of more than one images .e.g.[[x, y, w, h], [x, y, w, h], ...].
shape : list of 2 int or None
【height, width].
Returns
-------
list of list of 4 numbers
A list of new bounding boxes.
Examples
---------
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50], [10, 10, 20, 20]], shape=[100, 100])
>>> print(coords)
[[0.3, 0.4, 0.5, 0.5], [0.1, 0.1, 0.2, 0.2]]
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[50, 100])
>>> print(coords)
[[0.3, 0.8, 0.5, 1.0]]
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[100, 200])
>>> print(coords)
[[0.15, 0.4, 0.25, 0.5]]
Returns
-------
list of 4 numbers
New coordinates.
"""
if coords is None:
coords = []
if shape is None:
shape = [100, 200]
imh, imw = shape[0], shape[1]
imh = imh * 1.0 # * 1.0 for python2 : force division to be float point
imw = imw * 1.0
coords_new = list()
for coord in coords:
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
x = coord[0] / imw
y = coord[1] / imh
w = coord[2] / imw
h = coord[3] / imh
coords_new.append([x, y, w, h])
return coords_new | [
"def",
"obj_box_coords_rescale",
"(",
"coords",
"=",
"None",
",",
"shape",
"=",
"None",
")",
":",
"if",
"coords",
"is",
"None",
":",
"coords",
"=",
"[",
"]",
"if",
"shape",
"is",
"None",
":",
"shape",
"=",
"[",
"100",
",",
"200",
"]",
"imh",
",",
"imw",
"=",
"shape",
"[",
"0",
"]",
",",
"shape",
"[",
"1",
"]",
"imh",
"=",
"imh",
"*",
"1.0",
"# * 1.0 for python2 : force division to be float point",
"imw",
"=",
"imw",
"*",
"1.0",
"coords_new",
"=",
"list",
"(",
")",
"for",
"coord",
"in",
"coords",
":",
"if",
"len",
"(",
"coord",
")",
"!=",
"4",
":",
"raise",
"AssertionError",
"(",
"\"coordinate should be 4 values : [x, y, w, h]\"",
")",
"x",
"=",
"coord",
"[",
"0",
"]",
"/",
"imw",
"y",
"=",
"coord",
"[",
"1",
"]",
"/",
"imh",
"w",
"=",
"coord",
"[",
"2",
"]",
"/",
"imw",
"h",
"=",
"coord",
"[",
"3",
"]",
"/",
"imh",
"coords_new",
".",
"append",
"(",
"[",
"x",
",",
"y",
",",
"w",
",",
"h",
"]",
")",
"return",
"coords_new"
] | Scale down a list of coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1].
Parameters
------------
coords : list of list of 4 ints or None
For coordinates of more than one images .e.g.[[x, y, w, h], [x, y, w, h], ...].
shape : list of 2 int or None
【height, width].
Returns
-------
list of list of 4 numbers
A list of new bounding boxes.
Examples
---------
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50], [10, 10, 20, 20]], shape=[100, 100])
>>> print(coords)
[[0.3, 0.4, 0.5, 0.5], [0.1, 0.1, 0.2, 0.2]]
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[50, 100])
>>> print(coords)
[[0.3, 0.8, 0.5, 1.0]]
>>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[100, 200])
>>> print(coords)
[[0.15, 0.4, 0.25, 0.5]]
Returns
-------
list of 4 numbers
New coordinates. | [
"Scale",
"down",
"a",
"list",
"of",
"coordinates",
"from",
"pixel",
"unit",
"to",
"the",
"ratio",
"of",
"image",
"size",
"i",
".",
"e",
".",
"in",
"the",
"range",
"of",
"[",
"0",
"1",
"]",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2376-L2429 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_coord_rescale | def obj_box_coord_rescale(coord=None, shape=None):
"""Scale down one coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1].
It is the reverse process of ``obj_box_coord_scale_to_pixelunit``.
Parameters
------------
coords : list of 4 int or None
One coordinates of one image e.g. [x, y, w, h].
shape : list of 2 int or None
For [height, width].
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> coord = tl.prepro.obj_box_coord_rescale(coord=[30, 40, 50, 50], shape=[100, 100])
[0.3, 0.4, 0.5, 0.5]
"""
if coord is None:
coord = []
if shape is None:
shape = [100, 200]
return obj_box_coords_rescale(coords=[coord], shape=shape)[0] | python | def obj_box_coord_rescale(coord=None, shape=None):
"""Scale down one coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1].
It is the reverse process of ``obj_box_coord_scale_to_pixelunit``.
Parameters
------------
coords : list of 4 int or None
One coordinates of one image e.g. [x, y, w, h].
shape : list of 2 int or None
For [height, width].
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> coord = tl.prepro.obj_box_coord_rescale(coord=[30, 40, 50, 50], shape=[100, 100])
[0.3, 0.4, 0.5, 0.5]
"""
if coord is None:
coord = []
if shape is None:
shape = [100, 200]
return obj_box_coords_rescale(coords=[coord], shape=shape)[0] | [
"def",
"obj_box_coord_rescale",
"(",
"coord",
"=",
"None",
",",
"shape",
"=",
"None",
")",
":",
"if",
"coord",
"is",
"None",
":",
"coord",
"=",
"[",
"]",
"if",
"shape",
"is",
"None",
":",
"shape",
"=",
"[",
"100",
",",
"200",
"]",
"return",
"obj_box_coords_rescale",
"(",
"coords",
"=",
"[",
"coord",
"]",
",",
"shape",
"=",
"shape",
")",
"[",
"0",
"]"
] | Scale down one coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1].
It is the reverse process of ``obj_box_coord_scale_to_pixelunit``.
Parameters
------------
coords : list of 4 int or None
One coordinates of one image e.g. [x, y, w, h].
shape : list of 2 int or None
For [height, width].
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> coord = tl.prepro.obj_box_coord_rescale(coord=[30, 40, 50, 50], shape=[100, 100])
[0.3, 0.4, 0.5, 0.5] | [
"Scale",
"down",
"one",
"coordinates",
"from",
"pixel",
"unit",
"to",
"the",
"ratio",
"of",
"image",
"size",
"i",
".",
"e",
".",
"in",
"the",
"range",
"of",
"[",
"0",
"1",
"]",
".",
"It",
"is",
"the",
"reverse",
"process",
"of",
"obj_box_coord_scale_to_pixelunit",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2432-L2459 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_coord_scale_to_pixelunit | def obj_box_coord_scale_to_pixelunit(coord, shape=None):
"""Convert one coordinate [x, y, w (or x2), h (or y2)] in ratio format to image coordinate format.
It is the reverse process of ``obj_box_coord_rescale``.
Parameters
-----------
coord : list of 4 float
One coordinate of one image [x, y, w (or x2), h (or y2)] in ratio format, i.e value range [0~1].
shape : tuple of 2 or None
For [height, width].
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> x, y, x2, y2 = tl.prepro.obj_box_coord_scale_to_pixelunit([0.2, 0.3, 0.5, 0.7], shape=(100, 200, 3))
[40, 30, 100, 70]
"""
if shape is None:
shape = [100, 100]
imh, imw = shape[0:2]
x = int(coord[0] * imw)
x2 = int(coord[2] * imw)
y = int(coord[1] * imh)
y2 = int(coord[3] * imh)
return [x, y, x2, y2] | python | def obj_box_coord_scale_to_pixelunit(coord, shape=None):
"""Convert one coordinate [x, y, w (or x2), h (or y2)] in ratio format to image coordinate format.
It is the reverse process of ``obj_box_coord_rescale``.
Parameters
-----------
coord : list of 4 float
One coordinate of one image [x, y, w (or x2), h (or y2)] in ratio format, i.e value range [0~1].
shape : tuple of 2 or None
For [height, width].
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> x, y, x2, y2 = tl.prepro.obj_box_coord_scale_to_pixelunit([0.2, 0.3, 0.5, 0.7], shape=(100, 200, 3))
[40, 30, 100, 70]
"""
if shape is None:
shape = [100, 100]
imh, imw = shape[0:2]
x = int(coord[0] * imw)
x2 = int(coord[2] * imw)
y = int(coord[1] * imh)
y2 = int(coord[3] * imh)
return [x, y, x2, y2] | [
"def",
"obj_box_coord_scale_to_pixelunit",
"(",
"coord",
",",
"shape",
"=",
"None",
")",
":",
"if",
"shape",
"is",
"None",
":",
"shape",
"=",
"[",
"100",
",",
"100",
"]",
"imh",
",",
"imw",
"=",
"shape",
"[",
"0",
":",
"2",
"]",
"x",
"=",
"int",
"(",
"coord",
"[",
"0",
"]",
"*",
"imw",
")",
"x2",
"=",
"int",
"(",
"coord",
"[",
"2",
"]",
"*",
"imw",
")",
"y",
"=",
"int",
"(",
"coord",
"[",
"1",
"]",
"*",
"imh",
")",
"y2",
"=",
"int",
"(",
"coord",
"[",
"3",
"]",
"*",
"imh",
")",
"return",
"[",
"x",
",",
"y",
",",
"x2",
",",
"y2",
"]"
] | Convert one coordinate [x, y, w (or x2), h (or y2)] in ratio format to image coordinate format.
It is the reverse process of ``obj_box_coord_rescale``.
Parameters
-----------
coord : list of 4 float
One coordinate of one image [x, y, w (or x2), h (or y2)] in ratio format, i.e value range [0~1].
shape : tuple of 2 or None
For [height, width].
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> x, y, x2, y2 = tl.prepro.obj_box_coord_scale_to_pixelunit([0.2, 0.3, 0.5, 0.7], shape=(100, 200, 3))
[40, 30, 100, 70] | [
"Convert",
"one",
"coordinate",
"[",
"x",
"y",
"w",
"(",
"or",
"x2",
")",
"h",
"(",
"or",
"y2",
")",
"]",
"in",
"ratio",
"format",
"to",
"image",
"coordinate",
"format",
".",
"It",
"is",
"the",
"reverse",
"process",
"of",
"obj_box_coord_rescale",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2462-L2492 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_coord_centroid_to_upleft_butright | def obj_box_coord_centroid_to_upleft_butright(coord, to_int=False):
"""Convert one coordinate [x_center, y_center, w, h] to [x1, y1, x2, y2] in up-left and botton-right format.
Parameters
------------
coord : list of 4 int/float
One coordinate.
to_int : boolean
Whether to convert output as integer.
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> coord = obj_box_coord_centroid_to_upleft_butright([30, 40, 20, 20])
[20, 30, 40, 50]
"""
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
x_center, y_center, w, h = coord
x = x_center - w / 2.
y = y_center - h / 2.
x2 = x + w
y2 = y + h
if to_int:
return [int(x), int(y), int(x2), int(y2)]
else:
return [x, y, x2, y2] | python | def obj_box_coord_centroid_to_upleft_butright(coord, to_int=False):
"""Convert one coordinate [x_center, y_center, w, h] to [x1, y1, x2, y2] in up-left and botton-right format.
Parameters
------------
coord : list of 4 int/float
One coordinate.
to_int : boolean
Whether to convert output as integer.
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> coord = obj_box_coord_centroid_to_upleft_butright([30, 40, 20, 20])
[20, 30, 40, 50]
"""
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
x_center, y_center, w, h = coord
x = x_center - w / 2.
y = y_center - h / 2.
x2 = x + w
y2 = y + h
if to_int:
return [int(x), int(y), int(x2), int(y2)]
else:
return [x, y, x2, y2] | [
"def",
"obj_box_coord_centroid_to_upleft_butright",
"(",
"coord",
",",
"to_int",
"=",
"False",
")",
":",
"if",
"len",
"(",
"coord",
")",
"!=",
"4",
":",
"raise",
"AssertionError",
"(",
"\"coordinate should be 4 values : [x, y, w, h]\"",
")",
"x_center",
",",
"y_center",
",",
"w",
",",
"h",
"=",
"coord",
"x",
"=",
"x_center",
"-",
"w",
"/",
"2.",
"y",
"=",
"y_center",
"-",
"h",
"/",
"2.",
"x2",
"=",
"x",
"+",
"w",
"y2",
"=",
"y",
"+",
"h",
"if",
"to_int",
":",
"return",
"[",
"int",
"(",
"x",
")",
",",
"int",
"(",
"y",
")",
",",
"int",
"(",
"x2",
")",
",",
"int",
"(",
"y2",
")",
"]",
"else",
":",
"return",
"[",
"x",
",",
"y",
",",
"x2",
",",
"y2",
"]"
] | Convert one coordinate [x_center, y_center, w, h] to [x1, y1, x2, y2] in up-left and botton-right format.
Parameters
------------
coord : list of 4 int/float
One coordinate.
to_int : boolean
Whether to convert output as integer.
Returns
-------
list of 4 numbers
New bounding box.
Examples
---------
>>> coord = obj_box_coord_centroid_to_upleft_butright([30, 40, 20, 20])
[20, 30, 40, 50] | [
"Convert",
"one",
"coordinate",
"[",
"x_center",
"y_center",
"w",
"h",
"]",
"to",
"[",
"x1",
"y1",
"x2",
"y2",
"]",
"in",
"up",
"-",
"left",
"and",
"botton",
"-",
"right",
"format",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2507-L2539 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_coord_upleft_butright_to_centroid | def obj_box_coord_upleft_butright_to_centroid(coord):
"""Convert one coordinate [x1, y1, x2, y2] to [x_center, y_center, w, h].
It is the reverse process of ``obj_box_coord_centroid_to_upleft_butright``.
Parameters
------------
coord : list of 4 int/float
One coordinate.
Returns
-------
list of 4 numbers
New bounding box.
"""
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x1, y1, x2, y2]")
x1, y1, x2, y2 = coord
w = x2 - x1
h = y2 - y1
x_c = x1 + w / 2.
y_c = y1 + h / 2.
return [x_c, y_c, w, h] | python | def obj_box_coord_upleft_butright_to_centroid(coord):
"""Convert one coordinate [x1, y1, x2, y2] to [x_center, y_center, w, h].
It is the reverse process of ``obj_box_coord_centroid_to_upleft_butright``.
Parameters
------------
coord : list of 4 int/float
One coordinate.
Returns
-------
list of 4 numbers
New bounding box.
"""
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x1, y1, x2, y2]")
x1, y1, x2, y2 = coord
w = x2 - x1
h = y2 - y1
x_c = x1 + w / 2.
y_c = y1 + h / 2.
return [x_c, y_c, w, h] | [
"def",
"obj_box_coord_upleft_butright_to_centroid",
"(",
"coord",
")",
":",
"if",
"len",
"(",
"coord",
")",
"!=",
"4",
":",
"raise",
"AssertionError",
"(",
"\"coordinate should be 4 values : [x1, y1, x2, y2]\"",
")",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"=",
"coord",
"w",
"=",
"x2",
"-",
"x1",
"h",
"=",
"y2",
"-",
"y1",
"x_c",
"=",
"x1",
"+",
"w",
"/",
"2.",
"y_c",
"=",
"y1",
"+",
"h",
"/",
"2.",
"return",
"[",
"x_c",
",",
"y_c",
",",
"w",
",",
"h",
"]"
] | Convert one coordinate [x1, y1, x2, y2] to [x_center, y_center, w, h].
It is the reverse process of ``obj_box_coord_centroid_to_upleft_butright``.
Parameters
------------
coord : list of 4 int/float
One coordinate.
Returns
-------
list of 4 numbers
New bounding box. | [
"Convert",
"one",
"coordinate",
"[",
"x1",
"y1",
"x2",
"y2",
"]",
"to",
"[",
"x_center",
"y_center",
"w",
"h",
"]",
".",
"It",
"is",
"the",
"reverse",
"process",
"of",
"obj_box_coord_centroid_to_upleft_butright",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2547-L2569 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_coord_centroid_to_upleft | def obj_box_coord_centroid_to_upleft(coord):
"""Convert one coordinate [x_center, y_center, w, h] to [x, y, w, h].
It is the reverse process of ``obj_box_coord_upleft_to_centroid``.
Parameters
------------
coord : list of 4 int/float
One coordinate.
Returns
-------
list of 4 numbers
New bounding box.
"""
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
x_center, y_center, w, h = coord
x = x_center - w / 2.
y = y_center - h / 2.
return [x, y, w, h] | python | def obj_box_coord_centroid_to_upleft(coord):
"""Convert one coordinate [x_center, y_center, w, h] to [x, y, w, h].
It is the reverse process of ``obj_box_coord_upleft_to_centroid``.
Parameters
------------
coord : list of 4 int/float
One coordinate.
Returns
-------
list of 4 numbers
New bounding box.
"""
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
x_center, y_center, w, h = coord
x = x_center - w / 2.
y = y_center - h / 2.
return [x, y, w, h] | [
"def",
"obj_box_coord_centroid_to_upleft",
"(",
"coord",
")",
":",
"if",
"len",
"(",
"coord",
")",
"!=",
"4",
":",
"raise",
"AssertionError",
"(",
"\"coordinate should be 4 values : [x, y, w, h]\"",
")",
"x_center",
",",
"y_center",
",",
"w",
",",
"h",
"=",
"coord",
"x",
"=",
"x_center",
"-",
"w",
"/",
"2.",
"y",
"=",
"y_center",
"-",
"h",
"/",
"2.",
"return",
"[",
"x",
",",
"y",
",",
"w",
",",
"h",
"]"
] | Convert one coordinate [x_center, y_center, w, h] to [x, y, w, h].
It is the reverse process of ``obj_box_coord_upleft_to_centroid``.
Parameters
------------
coord : list of 4 int/float
One coordinate.
Returns
-------
list of 4 numbers
New bounding box. | [
"Convert",
"one",
"coordinate",
"[",
"x_center",
"y_center",
"w",
"h",
"]",
"to",
"[",
"x",
"y",
"w",
"h",
"]",
".",
"It",
"is",
"the",
"reverse",
"process",
"of",
"obj_box_coord_upleft_to_centroid",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2572-L2593 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | parse_darknet_ann_str_to_list | def parse_darknet_ann_str_to_list(annotations):
r"""Input string format of class, x, y, w, h, return list of list format.
Parameters
-----------
annotations : str
The annotations in darkent format "class, x, y, w, h ...." seperated by "\\n".
Returns
-------
list of list of 4 numbers
List of bounding box.
"""
annotations = annotations.split("\n")
ann = []
for a in annotations:
a = a.split()
if len(a) == 5:
for i, _v in enumerate(a):
if i == 0:
a[i] = int(a[i])
else:
a[i] = float(a[i])
ann.append(a)
return ann | python | def parse_darknet_ann_str_to_list(annotations):
r"""Input string format of class, x, y, w, h, return list of list format.
Parameters
-----------
annotations : str
The annotations in darkent format "class, x, y, w, h ...." seperated by "\\n".
Returns
-------
list of list of 4 numbers
List of bounding box.
"""
annotations = annotations.split("\n")
ann = []
for a in annotations:
a = a.split()
if len(a) == 5:
for i, _v in enumerate(a):
if i == 0:
a[i] = int(a[i])
else:
a[i] = float(a[i])
ann.append(a)
return ann | [
"def",
"parse_darknet_ann_str_to_list",
"(",
"annotations",
")",
":",
"annotations",
"=",
"annotations",
".",
"split",
"(",
"\"\\n\"",
")",
"ann",
"=",
"[",
"]",
"for",
"a",
"in",
"annotations",
":",
"a",
"=",
"a",
".",
"split",
"(",
")",
"if",
"len",
"(",
"a",
")",
"==",
"5",
":",
"for",
"i",
",",
"_v",
"in",
"enumerate",
"(",
"a",
")",
":",
"if",
"i",
"==",
"0",
":",
"a",
"[",
"i",
"]",
"=",
"int",
"(",
"a",
"[",
"i",
"]",
")",
"else",
":",
"a",
"[",
"i",
"]",
"=",
"float",
"(",
"a",
"[",
"i",
"]",
")",
"ann",
".",
"append",
"(",
"a",
")",
"return",
"ann"
] | r"""Input string format of class, x, y, w, h, return list of list format.
Parameters
-----------
annotations : str
The annotations in darkent format "class, x, y, w, h ...." seperated by "\\n".
Returns
-------
list of list of 4 numbers
List of bounding box. | [
"r",
"Input",
"string",
"format",
"of",
"class",
"x",
"y",
"w",
"h",
"return",
"list",
"of",
"list",
"format",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2620-L2645 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | parse_darknet_ann_list_to_cls_box | def parse_darknet_ann_list_to_cls_box(annotations):
"""Parse darknet annotation format into two lists for class and bounding box.
Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].
Parameters
------------
annotations : list of list
A list of class and bounding boxes of images e.g. [[class, x, y, w, h], ...]
Returns
-------
list of int
List of class labels.
list of list of 4 numbers
List of bounding box.
"""
class_list = []
bbox_list = []
for ann in annotations:
class_list.append(ann[0])
bbox_list.append(ann[1:])
return class_list, bbox_list | python | def parse_darknet_ann_list_to_cls_box(annotations):
"""Parse darknet annotation format into two lists for class and bounding box.
Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].
Parameters
------------
annotations : list of list
A list of class and bounding boxes of images e.g. [[class, x, y, w, h], ...]
Returns
-------
list of int
List of class labels.
list of list of 4 numbers
List of bounding box.
"""
class_list = []
bbox_list = []
for ann in annotations:
class_list.append(ann[0])
bbox_list.append(ann[1:])
return class_list, bbox_list | [
"def",
"parse_darknet_ann_list_to_cls_box",
"(",
"annotations",
")",
":",
"class_list",
"=",
"[",
"]",
"bbox_list",
"=",
"[",
"]",
"for",
"ann",
"in",
"annotations",
":",
"class_list",
".",
"append",
"(",
"ann",
"[",
"0",
"]",
")",
"bbox_list",
".",
"append",
"(",
"ann",
"[",
"1",
":",
"]",
")",
"return",
"class_list",
",",
"bbox_list"
] | Parse darknet annotation format into two lists for class and bounding box.
Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].
Parameters
------------
annotations : list of list
A list of class and bounding boxes of images e.g. [[class, x, y, w, h], ...]
Returns
-------
list of int
List of class labels.
list of list of 4 numbers
List of bounding box. | [
"Parse",
"darknet",
"annotation",
"format",
"into",
"two",
"lists",
"for",
"class",
"and",
"bounding",
"box",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2648-L2672 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_horizontal_flip | def obj_box_horizontal_flip(im, coords=None, is_rescale=False, is_center=False, is_random=False):
"""Left-right flip the image and coordinates for object detection.
Parameters
----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...].
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
is_random : boolean
If True, randomly flip. Default is False.
Returns
-------
numpy.array
A processed image
list of list of 4 numbers
A list of new bounding boxes.
Examples
--------
>>> im = np.zeros([80, 100]) # as an image with shape width=100, height=80
>>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False)
>>> print(coords)
[[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False)
>>> print(coords)
[[0.5, 0.4, 0.3, 0.3]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False)
>>> print(coords)
[[80, 40, 30, 30]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False)
>>> print(coords)
[[50, 40, 30, 30]]
"""
if coords is None:
coords = []
def _flip(im, coords):
im = flip_axis(im, axis=1, is_random=False)
coords_new = list()
for coord in coords:
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
if is_rescale:
if is_center:
# x_center' = 1 - x
x = 1. - coord[0]
else:
# x_center' = 1 - x - w
x = 1. - coord[0] - coord[2]
else:
if is_center:
# x' = im.width - x
x = im.shape[1] - coord[0]
else:
# x' = im.width - x - w
x = im.shape[1] - coord[0] - coord[2]
coords_new.append([x, coord[1], coord[2], coord[3]])
return im, coords_new
if is_random:
factor = np.random.uniform(-1, 1)
if factor > 0:
return _flip(im, coords)
else:
return im, coords
else:
return _flip(im, coords) | python | def obj_box_horizontal_flip(im, coords=None, is_rescale=False, is_center=False, is_random=False):
"""Left-right flip the image and coordinates for object detection.
Parameters
----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...].
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
is_random : boolean
If True, randomly flip. Default is False.
Returns
-------
numpy.array
A processed image
list of list of 4 numbers
A list of new bounding boxes.
Examples
--------
>>> im = np.zeros([80, 100]) # as an image with shape width=100, height=80
>>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False)
>>> print(coords)
[[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False)
>>> print(coords)
[[0.5, 0.4, 0.3, 0.3]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False)
>>> print(coords)
[[80, 40, 30, 30]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False)
>>> print(coords)
[[50, 40, 30, 30]]
"""
if coords is None:
coords = []
def _flip(im, coords):
im = flip_axis(im, axis=1, is_random=False)
coords_new = list()
for coord in coords:
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
if is_rescale:
if is_center:
# x_center' = 1 - x
x = 1. - coord[0]
else:
# x_center' = 1 - x - w
x = 1. - coord[0] - coord[2]
else:
if is_center:
# x' = im.width - x
x = im.shape[1] - coord[0]
else:
# x' = im.width - x - w
x = im.shape[1] - coord[0] - coord[2]
coords_new.append([x, coord[1], coord[2], coord[3]])
return im, coords_new
if is_random:
factor = np.random.uniform(-1, 1)
if factor > 0:
return _flip(im, coords)
else:
return im, coords
else:
return _flip(im, coords) | [
"def",
"obj_box_horizontal_flip",
"(",
"im",
",",
"coords",
"=",
"None",
",",
"is_rescale",
"=",
"False",
",",
"is_center",
"=",
"False",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"coords",
"is",
"None",
":",
"coords",
"=",
"[",
"]",
"def",
"_flip",
"(",
"im",
",",
"coords",
")",
":",
"im",
"=",
"flip_axis",
"(",
"im",
",",
"axis",
"=",
"1",
",",
"is_random",
"=",
"False",
")",
"coords_new",
"=",
"list",
"(",
")",
"for",
"coord",
"in",
"coords",
":",
"if",
"len",
"(",
"coord",
")",
"!=",
"4",
":",
"raise",
"AssertionError",
"(",
"\"coordinate should be 4 values : [x, y, w, h]\"",
")",
"if",
"is_rescale",
":",
"if",
"is_center",
":",
"# x_center' = 1 - x",
"x",
"=",
"1.",
"-",
"coord",
"[",
"0",
"]",
"else",
":",
"# x_center' = 1 - x - w",
"x",
"=",
"1.",
"-",
"coord",
"[",
"0",
"]",
"-",
"coord",
"[",
"2",
"]",
"else",
":",
"if",
"is_center",
":",
"# x' = im.width - x",
"x",
"=",
"im",
".",
"shape",
"[",
"1",
"]",
"-",
"coord",
"[",
"0",
"]",
"else",
":",
"# x' = im.width - x - w",
"x",
"=",
"im",
".",
"shape",
"[",
"1",
"]",
"-",
"coord",
"[",
"0",
"]",
"-",
"coord",
"[",
"2",
"]",
"coords_new",
".",
"append",
"(",
"[",
"x",
",",
"coord",
"[",
"1",
"]",
",",
"coord",
"[",
"2",
"]",
",",
"coord",
"[",
"3",
"]",
"]",
")",
"return",
"im",
",",
"coords_new",
"if",
"is_random",
":",
"factor",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
")",
"if",
"factor",
">",
"0",
":",
"return",
"_flip",
"(",
"im",
",",
"coords",
")",
"else",
":",
"return",
"im",
",",
"coords",
"else",
":",
"return",
"_flip",
"(",
"im",
",",
"coords",
")"
] | Left-right flip the image and coordinates for object detection.
Parameters
----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...].
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
is_random : boolean
If True, randomly flip. Default is False.
Returns
-------
numpy.array
A processed image
list of list of 4 numbers
A list of new bounding boxes.
Examples
--------
>>> im = np.zeros([80, 100]) # as an image with shape width=100, height=80
>>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False)
>>> print(coords)
[[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False)
>>> print(coords)
[[0.5, 0.4, 0.3, 0.3]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False)
>>> print(coords)
[[80, 40, 30, 30]]
>>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False)
>>> print(coords)
[[50, 40, 30, 30]] | [
"Left",
"-",
"right",
"flip",
"the",
"image",
"and",
"coordinates",
"for",
"object",
"detection",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2675-L2751 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_imresize | def obj_box_imresize(im, coords=None, size=None, interp='bicubic', mode=None, is_rescale=False):
"""Resize an image, and compute the new bounding box coordinates.
Parameters
-------------
im : numpy.array
An image with dimension of [row, col, channel] (default).
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
size interp and mode : args
See ``tl.prepro.imresize``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1], then return the original coordinates. Default is False.
Returns
-------
numpy.array
A processed image
list of list of 4 numbers
A list of new bounding boxes.
Examples
--------
>>> im = np.zeros([80, 100, 3]) # as an image with shape width=100, height=80
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False)
>>> print(coords)
[[40, 80, 60, 60], [20, 40, 40, 40]]
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False)
>>> print(coords)
[[20, 20, 30, 15]]
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False)
>>> print(coords)
[[30, 30, 45, 22]]
>>> im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True)
>>> print(coords, im2.shape)
[[0.2, 0.4, 0.3, 0.3]] (160, 200, 3)
"""
if coords is None:
coords = []
if size is None:
size = [100, 100]
imh, imw = im.shape[0:2]
imh = imh * 1.0 # * 1.0 for python2 : force division to be float point
imw = imw * 1.0
im = imresize(im, size=size, interp=interp, mode=mode)
if is_rescale is False:
coords_new = list()
for coord in coords:
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
# x' = x * (imw'/imw)
x = int(coord[0] * (size[1] / imw))
# y' = y * (imh'/imh)
# tl.logging.info('>>', coord[1], size[0], imh)
y = int(coord[1] * (size[0] / imh))
# w' = w * (imw'/imw)
w = int(coord[2] * (size[1] / imw))
# h' = h * (imh'/imh)
h = int(coord[3] * (size[0] / imh))
coords_new.append([x, y, w, h])
return im, coords_new
else:
return im, coords | python | def obj_box_imresize(im, coords=None, size=None, interp='bicubic', mode=None, is_rescale=False):
"""Resize an image, and compute the new bounding box coordinates.
Parameters
-------------
im : numpy.array
An image with dimension of [row, col, channel] (default).
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
size interp and mode : args
See ``tl.prepro.imresize``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1], then return the original coordinates. Default is False.
Returns
-------
numpy.array
A processed image
list of list of 4 numbers
A list of new bounding boxes.
Examples
--------
>>> im = np.zeros([80, 100, 3]) # as an image with shape width=100, height=80
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False)
>>> print(coords)
[[40, 80, 60, 60], [20, 40, 40, 40]]
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False)
>>> print(coords)
[[20, 20, 30, 15]]
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False)
>>> print(coords)
[[30, 30, 45, 22]]
>>> im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True)
>>> print(coords, im2.shape)
[[0.2, 0.4, 0.3, 0.3]] (160, 200, 3)
"""
if coords is None:
coords = []
if size is None:
size = [100, 100]
imh, imw = im.shape[0:2]
imh = imh * 1.0 # * 1.0 for python2 : force division to be float point
imw = imw * 1.0
im = imresize(im, size=size, interp=interp, mode=mode)
if is_rescale is False:
coords_new = list()
for coord in coords:
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
# x' = x * (imw'/imw)
x = int(coord[0] * (size[1] / imw))
# y' = y * (imh'/imh)
# tl.logging.info('>>', coord[1], size[0], imh)
y = int(coord[1] * (size[0] / imh))
# w' = w * (imw'/imw)
w = int(coord[2] * (size[1] / imw))
# h' = h * (imh'/imh)
h = int(coord[3] * (size[0] / imh))
coords_new.append([x, y, w, h])
return im, coords_new
else:
return im, coords | [
"def",
"obj_box_imresize",
"(",
"im",
",",
"coords",
"=",
"None",
",",
"size",
"=",
"None",
",",
"interp",
"=",
"'bicubic'",
",",
"mode",
"=",
"None",
",",
"is_rescale",
"=",
"False",
")",
":",
"if",
"coords",
"is",
"None",
":",
"coords",
"=",
"[",
"]",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"[",
"100",
",",
"100",
"]",
"imh",
",",
"imw",
"=",
"im",
".",
"shape",
"[",
"0",
":",
"2",
"]",
"imh",
"=",
"imh",
"*",
"1.0",
"# * 1.0 for python2 : force division to be float point",
"imw",
"=",
"imw",
"*",
"1.0",
"im",
"=",
"imresize",
"(",
"im",
",",
"size",
"=",
"size",
",",
"interp",
"=",
"interp",
",",
"mode",
"=",
"mode",
")",
"if",
"is_rescale",
"is",
"False",
":",
"coords_new",
"=",
"list",
"(",
")",
"for",
"coord",
"in",
"coords",
":",
"if",
"len",
"(",
"coord",
")",
"!=",
"4",
":",
"raise",
"AssertionError",
"(",
"\"coordinate should be 4 values : [x, y, w, h]\"",
")",
"# x' = x * (imw'/imw)",
"x",
"=",
"int",
"(",
"coord",
"[",
"0",
"]",
"*",
"(",
"size",
"[",
"1",
"]",
"/",
"imw",
")",
")",
"# y' = y * (imh'/imh)",
"# tl.logging.info('>>', coord[1], size[0], imh)",
"y",
"=",
"int",
"(",
"coord",
"[",
"1",
"]",
"*",
"(",
"size",
"[",
"0",
"]",
"/",
"imh",
")",
")",
"# w' = w * (imw'/imw)",
"w",
"=",
"int",
"(",
"coord",
"[",
"2",
"]",
"*",
"(",
"size",
"[",
"1",
"]",
"/",
"imw",
")",
")",
"# h' = h * (imh'/imh)",
"h",
"=",
"int",
"(",
"coord",
"[",
"3",
"]",
"*",
"(",
"size",
"[",
"0",
"]",
"/",
"imh",
")",
")",
"coords_new",
".",
"append",
"(",
"[",
"x",
",",
"y",
",",
"w",
",",
"h",
"]",
")",
"return",
"im",
",",
"coords_new",
"else",
":",
"return",
"im",
",",
"coords"
] | Resize an image, and compute the new bounding box coordinates.
Parameters
-------------
im : numpy.array
An image with dimension of [row, col, channel] (default).
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
size interp and mode : args
See ``tl.prepro.imresize``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1], then return the original coordinates. Default is False.
Returns
-------
numpy.array
A processed image
list of list of 4 numbers
A list of new bounding boxes.
Examples
--------
>>> im = np.zeros([80, 100, 3]) # as an image with shape width=100, height=80
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False)
>>> print(coords)
[[40, 80, 60, 60], [20, 40, 40, 40]]
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False)
>>> print(coords)
[[20, 20, 30, 15]]
>>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False)
>>> print(coords)
[[30, 30, 45, 22]]
>>> im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True)
>>> print(coords, im2.shape)
[[0.2, 0.4, 0.3, 0.3]] (160, 200, 3) | [
"Resize",
"an",
"image",
"and",
"compute",
"the",
"new",
"bounding",
"box",
"coordinates",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2772-L2840 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_crop | def obj_box_crop(
im, classes=None, coords=None, wrg=100, hrg=100, is_rescale=False, is_center=False, is_random=False,
thresh_wh=0.02, thresh_wh2=12.
):
"""Randomly or centrally crop an image, and compute the new bounding box coordinates.
Objects outside the cropped image will be removed.
Parameters
-----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
classes : list of int or None
Class IDs.
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
wrg hrg and is_random : args
See ``tl.prepro.crop``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean, default False
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
thresh_wh : float
Threshold, remove the box if its ratio of width(height) to image size less than the threshold.
thresh_wh2 : float
Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold.
Returns
-------
numpy.array
A processed image
list of int
A list of classes
list of list of 4 numbers
A list of new bounding boxes.
"""
if classes is None:
classes = []
if coords is None:
coords = []
h, w = im.shape[0], im.shape[1]
if (h <= hrg) or (w <= wrg):
raise AssertionError("The size of cropping should smaller than the original image")
if is_random:
h_offset = int(np.random.uniform(0, h - hrg) - 1)
w_offset = int(np.random.uniform(0, w - wrg) - 1)
h_end = hrg + h_offset
w_end = wrg + w_offset
im_new = im[h_offset:h_end, w_offset:w_end]
else: # central crop
h_offset = int(np.floor((h - hrg) / 2.))
w_offset = int(np.floor((w - wrg) / 2.))
h_end = h_offset + hrg
w_end = w_offset + wrg
im_new = im[h_offset:h_end, w_offset:w_end]
# w
# _____________________________
# | h/w offset |
# | ------- |
# h | | | |
# | | | |
# | ------- |
# | h/w end |
# |___________________________|
def _get_coord(coord):
"""Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates,
before getting the new coordinates.
Boxes outsides the cropped image will be removed.
"""
if is_center:
coord = obj_box_coord_centroid_to_upleft(coord)
##======= pixel unit format and upleft, w, h ==========##
# x = np.clip( coord[0] - w_offset, 0, w_end - w_offset)
# y = np.clip( coord[1] - h_offset, 0, h_end - h_offset)
# w = np.clip( coord[2] , 0, w_end - w_offset)
# h = np.clip( coord[3] , 0, h_end - h_offset)
x = coord[0] - w_offset
y = coord[1] - h_offset
w = coord[2]
h = coord[3]
if x < 0:
if x + w <= 0:
return None
w = w + x
x = 0
elif x > im_new.shape[1]: # object outside the cropped image
return None
if y < 0:
if y + h <= 0:
return None
h = h + y
y = 0
elif y > im_new.shape[0]: # object outside the cropped image
return None
if (x is not None) and (x + w > im_new.shape[1]): # box outside the cropped image
w = im_new.shape[1] - x
if (y is not None) and (y + h > im_new.shape[0]): # box outside the cropped image
h = im_new.shape[0] - y
if (w / (h + 1.) > thresh_wh2) or (h / (w + 1.) > thresh_wh2): # object shape strange: too narrow
# tl.logging.info('xx', w, h)
return None
if (w / (im_new.shape[1] * 1.) < thresh_wh) or (h / (im_new.shape[0] * 1.) <
thresh_wh): # object shape strange: too narrow
# tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0])
return None
coord = [x, y, w, h]
## convert back if input format is center.
if is_center:
coord = obj_box_coord_upleft_to_centroid(coord)
return coord
coords_new = list()
classes_new = list()
for i, _ in enumerate(coords):
coord = coords[i]
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
if is_rescale:
# for scaled coord, upscaled before process and scale back in the end.
coord = obj_box_coord_scale_to_pixelunit(coord, im.shape)
coord = _get_coord(coord)
if coord is not None:
coord = obj_box_coord_rescale(coord, im_new.shape)
coords_new.append(coord)
classes_new.append(classes[i])
else:
coord = _get_coord(coord)
if coord is not None:
coords_new.append(coord)
classes_new.append(classes[i])
return im_new, classes_new, coords_new | python | def obj_box_crop(
im, classes=None, coords=None, wrg=100, hrg=100, is_rescale=False, is_center=False, is_random=False,
thresh_wh=0.02, thresh_wh2=12.
):
"""Randomly or centrally crop an image, and compute the new bounding box coordinates.
Objects outside the cropped image will be removed.
Parameters
-----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
classes : list of int or None
Class IDs.
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
wrg hrg and is_random : args
See ``tl.prepro.crop``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean, default False
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
thresh_wh : float
Threshold, remove the box if its ratio of width(height) to image size less than the threshold.
thresh_wh2 : float
Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold.
Returns
-------
numpy.array
A processed image
list of int
A list of classes
list of list of 4 numbers
A list of new bounding boxes.
"""
if classes is None:
classes = []
if coords is None:
coords = []
h, w = im.shape[0], im.shape[1]
if (h <= hrg) or (w <= wrg):
raise AssertionError("The size of cropping should smaller than the original image")
if is_random:
h_offset = int(np.random.uniform(0, h - hrg) - 1)
w_offset = int(np.random.uniform(0, w - wrg) - 1)
h_end = hrg + h_offset
w_end = wrg + w_offset
im_new = im[h_offset:h_end, w_offset:w_end]
else: # central crop
h_offset = int(np.floor((h - hrg) / 2.))
w_offset = int(np.floor((w - wrg) / 2.))
h_end = h_offset + hrg
w_end = w_offset + wrg
im_new = im[h_offset:h_end, w_offset:w_end]
# w
# _____________________________
# | h/w offset |
# | ------- |
# h | | | |
# | | | |
# | ------- |
# | h/w end |
# |___________________________|
def _get_coord(coord):
"""Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates,
before getting the new coordinates.
Boxes outsides the cropped image will be removed.
"""
if is_center:
coord = obj_box_coord_centroid_to_upleft(coord)
##======= pixel unit format and upleft, w, h ==========##
# x = np.clip( coord[0] - w_offset, 0, w_end - w_offset)
# y = np.clip( coord[1] - h_offset, 0, h_end - h_offset)
# w = np.clip( coord[2] , 0, w_end - w_offset)
# h = np.clip( coord[3] , 0, h_end - h_offset)
x = coord[0] - w_offset
y = coord[1] - h_offset
w = coord[2]
h = coord[3]
if x < 0:
if x + w <= 0:
return None
w = w + x
x = 0
elif x > im_new.shape[1]: # object outside the cropped image
return None
if y < 0:
if y + h <= 0:
return None
h = h + y
y = 0
elif y > im_new.shape[0]: # object outside the cropped image
return None
if (x is not None) and (x + w > im_new.shape[1]): # box outside the cropped image
w = im_new.shape[1] - x
if (y is not None) and (y + h > im_new.shape[0]): # box outside the cropped image
h = im_new.shape[0] - y
if (w / (h + 1.) > thresh_wh2) or (h / (w + 1.) > thresh_wh2): # object shape strange: too narrow
# tl.logging.info('xx', w, h)
return None
if (w / (im_new.shape[1] * 1.) < thresh_wh) or (h / (im_new.shape[0] * 1.) <
thresh_wh): # object shape strange: too narrow
# tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0])
return None
coord = [x, y, w, h]
## convert back if input format is center.
if is_center:
coord = obj_box_coord_upleft_to_centroid(coord)
return coord
coords_new = list()
classes_new = list()
for i, _ in enumerate(coords):
coord = coords[i]
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
if is_rescale:
# for scaled coord, upscaled before process and scale back in the end.
coord = obj_box_coord_scale_to_pixelunit(coord, im.shape)
coord = _get_coord(coord)
if coord is not None:
coord = obj_box_coord_rescale(coord, im_new.shape)
coords_new.append(coord)
classes_new.append(classes[i])
else:
coord = _get_coord(coord)
if coord is not None:
coords_new.append(coord)
classes_new.append(classes[i])
return im_new, classes_new, coords_new | [
"def",
"obj_box_crop",
"(",
"im",
",",
"classes",
"=",
"None",
",",
"coords",
"=",
"None",
",",
"wrg",
"=",
"100",
",",
"hrg",
"=",
"100",
",",
"is_rescale",
"=",
"False",
",",
"is_center",
"=",
"False",
",",
"is_random",
"=",
"False",
",",
"thresh_wh",
"=",
"0.02",
",",
"thresh_wh2",
"=",
"12.",
")",
":",
"if",
"classes",
"is",
"None",
":",
"classes",
"=",
"[",
"]",
"if",
"coords",
"is",
"None",
":",
"coords",
"=",
"[",
"]",
"h",
",",
"w",
"=",
"im",
".",
"shape",
"[",
"0",
"]",
",",
"im",
".",
"shape",
"[",
"1",
"]",
"if",
"(",
"h",
"<=",
"hrg",
")",
"or",
"(",
"w",
"<=",
"wrg",
")",
":",
"raise",
"AssertionError",
"(",
"\"The size of cropping should smaller than the original image\"",
")",
"if",
"is_random",
":",
"h_offset",
"=",
"int",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"h",
"-",
"hrg",
")",
"-",
"1",
")",
"w_offset",
"=",
"int",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"w",
"-",
"wrg",
")",
"-",
"1",
")",
"h_end",
"=",
"hrg",
"+",
"h_offset",
"w_end",
"=",
"wrg",
"+",
"w_offset",
"im_new",
"=",
"im",
"[",
"h_offset",
":",
"h_end",
",",
"w_offset",
":",
"w_end",
"]",
"else",
":",
"# central crop",
"h_offset",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"(",
"h",
"-",
"hrg",
")",
"/",
"2.",
")",
")",
"w_offset",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"(",
"w",
"-",
"wrg",
")",
"/",
"2.",
")",
")",
"h_end",
"=",
"h_offset",
"+",
"hrg",
"w_end",
"=",
"w_offset",
"+",
"wrg",
"im_new",
"=",
"im",
"[",
"h_offset",
":",
"h_end",
",",
"w_offset",
":",
"w_end",
"]",
"# w",
"# _____________________________",
"# | h/w offset |",
"# | ------- |",
"# h | | | |",
"# | | | |",
"# | ------- |",
"# | h/w end |",
"# |___________________________|",
"def",
"_get_coord",
"(",
"coord",
")",
":",
"\"\"\"Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates,\n before getting the new coordinates.\n Boxes outsides the cropped image will be removed.\n\n \"\"\"",
"if",
"is_center",
":",
"coord",
"=",
"obj_box_coord_centroid_to_upleft",
"(",
"coord",
")",
"##======= pixel unit format and upleft, w, h ==========##",
"# x = np.clip( coord[0] - w_offset, 0, w_end - w_offset)",
"# y = np.clip( coord[1] - h_offset, 0, h_end - h_offset)",
"# w = np.clip( coord[2] , 0, w_end - w_offset)",
"# h = np.clip( coord[3] , 0, h_end - h_offset)",
"x",
"=",
"coord",
"[",
"0",
"]",
"-",
"w_offset",
"y",
"=",
"coord",
"[",
"1",
"]",
"-",
"h_offset",
"w",
"=",
"coord",
"[",
"2",
"]",
"h",
"=",
"coord",
"[",
"3",
"]",
"if",
"x",
"<",
"0",
":",
"if",
"x",
"+",
"w",
"<=",
"0",
":",
"return",
"None",
"w",
"=",
"w",
"+",
"x",
"x",
"=",
"0",
"elif",
"x",
">",
"im_new",
".",
"shape",
"[",
"1",
"]",
":",
"# object outside the cropped image",
"return",
"None",
"if",
"y",
"<",
"0",
":",
"if",
"y",
"+",
"h",
"<=",
"0",
":",
"return",
"None",
"h",
"=",
"h",
"+",
"y",
"y",
"=",
"0",
"elif",
"y",
">",
"im_new",
".",
"shape",
"[",
"0",
"]",
":",
"# object outside the cropped image",
"return",
"None",
"if",
"(",
"x",
"is",
"not",
"None",
")",
"and",
"(",
"x",
"+",
"w",
">",
"im_new",
".",
"shape",
"[",
"1",
"]",
")",
":",
"# box outside the cropped image",
"w",
"=",
"im_new",
".",
"shape",
"[",
"1",
"]",
"-",
"x",
"if",
"(",
"y",
"is",
"not",
"None",
")",
"and",
"(",
"y",
"+",
"h",
">",
"im_new",
".",
"shape",
"[",
"0",
"]",
")",
":",
"# box outside the cropped image",
"h",
"=",
"im_new",
".",
"shape",
"[",
"0",
"]",
"-",
"y",
"if",
"(",
"w",
"/",
"(",
"h",
"+",
"1.",
")",
">",
"thresh_wh2",
")",
"or",
"(",
"h",
"/",
"(",
"w",
"+",
"1.",
")",
">",
"thresh_wh2",
")",
":",
"# object shape strange: too narrow",
"# tl.logging.info('xx', w, h)",
"return",
"None",
"if",
"(",
"w",
"/",
"(",
"im_new",
".",
"shape",
"[",
"1",
"]",
"*",
"1.",
")",
"<",
"thresh_wh",
")",
"or",
"(",
"h",
"/",
"(",
"im_new",
".",
"shape",
"[",
"0",
"]",
"*",
"1.",
")",
"<",
"thresh_wh",
")",
":",
"# object shape strange: too narrow",
"# tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0])",
"return",
"None",
"coord",
"=",
"[",
"x",
",",
"y",
",",
"w",
",",
"h",
"]",
"## convert back if input format is center.",
"if",
"is_center",
":",
"coord",
"=",
"obj_box_coord_upleft_to_centroid",
"(",
"coord",
")",
"return",
"coord",
"coords_new",
"=",
"list",
"(",
")",
"classes_new",
"=",
"list",
"(",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"coords",
")",
":",
"coord",
"=",
"coords",
"[",
"i",
"]",
"if",
"len",
"(",
"coord",
")",
"!=",
"4",
":",
"raise",
"AssertionError",
"(",
"\"coordinate should be 4 values : [x, y, w, h]\"",
")",
"if",
"is_rescale",
":",
"# for scaled coord, upscaled before process and scale back in the end.",
"coord",
"=",
"obj_box_coord_scale_to_pixelunit",
"(",
"coord",
",",
"im",
".",
"shape",
")",
"coord",
"=",
"_get_coord",
"(",
"coord",
")",
"if",
"coord",
"is",
"not",
"None",
":",
"coord",
"=",
"obj_box_coord_rescale",
"(",
"coord",
",",
"im_new",
".",
"shape",
")",
"coords_new",
".",
"append",
"(",
"coord",
")",
"classes_new",
".",
"append",
"(",
"classes",
"[",
"i",
"]",
")",
"else",
":",
"coord",
"=",
"_get_coord",
"(",
"coord",
")",
"if",
"coord",
"is",
"not",
"None",
":",
"coords_new",
".",
"append",
"(",
"coord",
")",
"classes_new",
".",
"append",
"(",
"classes",
"[",
"i",
"]",
")",
"return",
"im_new",
",",
"classes_new",
",",
"coords_new"
] | Randomly or centrally crop an image, and compute the new bounding box coordinates.
Objects outside the cropped image will be removed.
Parameters
-----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
classes : list of int or None
Class IDs.
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
wrg hrg and is_random : args
See ``tl.prepro.crop``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean, default False
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
thresh_wh : float
Threshold, remove the box if its ratio of width(height) to image size less than the threshold.
thresh_wh2 : float
Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold.
Returns
-------
numpy.array
A processed image
list of int
A list of classes
list of list of 4 numbers
A list of new bounding boxes. | [
"Randomly",
"or",
"centrally",
"crop",
"an",
"image",
"and",
"compute",
"the",
"new",
"bounding",
"box",
"coordinates",
".",
"Objects",
"outside",
"the",
"cropped",
"image",
"will",
"be",
"removed",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2859-L3009 | valid |
tensorlayer/tensorlayer | tensorlayer/prepro.py | obj_box_shift | def obj_box_shift(
im, classes=None, coords=None, wrg=0.1, hrg=0.1, row_index=0, col_index=1, channel_index=2, fill_mode='nearest',
cval=0., order=1, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12.
):
"""Shift an image randomly or non-randomly, and compute the new bounding box coordinates.
Objects outside the cropped image will be removed.
Parameters
-----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
classes : list of int or None
Class IDs.
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
wrg, hrg row_index col_index channel_index is_random fill_mode cval and order : see ``tl.prepro.shift``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
thresh_wh : float
Threshold, remove the box if its ratio of width(height) to image size less than the threshold.
thresh_wh2 : float
Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold.
Returns
-------
numpy.array
A processed image
list of int
A list of classes
list of list of 4 numbers
A list of new bounding boxes.
"""
if classes is None:
classes = []
if coords is None:
coords = []
imh, imw = im.shape[row_index], im.shape[col_index]
if (hrg >= 1.0) and (hrg <= 0.) and (wrg >= 1.0) and (wrg <= 0.):
raise AssertionError("shift range should be (0, 1)")
if is_random:
tx = np.random.uniform(-hrg, hrg) * imh
ty = np.random.uniform(-wrg, wrg) * imw
else:
tx, ty = hrg * imh, wrg * imw
translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
im_new = affine_transform(im, transform_matrix, channel_index, fill_mode, cval, order)
# modified from obj_box_crop
def _get_coord(coord):
"""Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates,
before getting the new coordinates.
Boxes outsides the cropped image will be removed.
"""
if is_center:
coord = obj_box_coord_centroid_to_upleft(coord)
##======= pixel unit format and upleft, w, h ==========##
x = coord[0] - ty # only change this
y = coord[1] - tx # only change this
w = coord[2]
h = coord[3]
if x < 0:
if x + w <= 0:
return None
w = w + x
x = 0
elif x > im_new.shape[1]: # object outside the cropped image
return None
if y < 0:
if y + h <= 0:
return None
h = h + y
y = 0
elif y > im_new.shape[0]: # object outside the cropped image
return None
if (x is not None) and (x + w > im_new.shape[1]): # box outside the cropped image
w = im_new.shape[1] - x
if (y is not None) and (y + h > im_new.shape[0]): # box outside the cropped image
h = im_new.shape[0] - y
if (w / (h + 1.) > thresh_wh2) or (h / (w + 1.) > thresh_wh2): # object shape strange: too narrow
# tl.logging.info('xx', w, h)
return None
if (w / (im_new.shape[1] * 1.) < thresh_wh) or (h / (im_new.shape[0] * 1.) <
thresh_wh): # object shape strange: too narrow
# tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0])
return None
coord = [x, y, w, h]
## convert back if input format is center.
if is_center:
coord = obj_box_coord_upleft_to_centroid(coord)
return coord
coords_new = list()
classes_new = list()
for i, _ in enumerate(coords):
coord = coords[i]
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
if is_rescale:
# for scaled coord, upscaled before process and scale back in the end.
coord = obj_box_coord_scale_to_pixelunit(coord, im.shape)
coord = _get_coord(coord)
if coord is not None:
coord = obj_box_coord_rescale(coord, im_new.shape)
coords_new.append(coord)
classes_new.append(classes[i])
else:
coord = _get_coord(coord)
if coord is not None:
coords_new.append(coord)
classes_new.append(classes[i])
return im_new, classes_new, coords_new | python | def obj_box_shift(
im, classes=None, coords=None, wrg=0.1, hrg=0.1, row_index=0, col_index=1, channel_index=2, fill_mode='nearest',
cval=0., order=1, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12.
):
"""Shift an image randomly or non-randomly, and compute the new bounding box coordinates.
Objects outside the cropped image will be removed.
Parameters
-----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
classes : list of int or None
Class IDs.
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
wrg, hrg row_index col_index channel_index is_random fill_mode cval and order : see ``tl.prepro.shift``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
thresh_wh : float
Threshold, remove the box if its ratio of width(height) to image size less than the threshold.
thresh_wh2 : float
Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold.
Returns
-------
numpy.array
A processed image
list of int
A list of classes
list of list of 4 numbers
A list of new bounding boxes.
"""
if classes is None:
classes = []
if coords is None:
coords = []
imh, imw = im.shape[row_index], im.shape[col_index]
if (hrg >= 1.0) and (hrg <= 0.) and (wrg >= 1.0) and (wrg <= 0.):
raise AssertionError("shift range should be (0, 1)")
if is_random:
tx = np.random.uniform(-hrg, hrg) * imh
ty = np.random.uniform(-wrg, wrg) * imw
else:
tx, ty = hrg * imh, wrg * imw
translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]])
transform_matrix = translation_matrix # no need to do offset
im_new = affine_transform(im, transform_matrix, channel_index, fill_mode, cval, order)
# modified from obj_box_crop
def _get_coord(coord):
"""Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates,
before getting the new coordinates.
Boxes outsides the cropped image will be removed.
"""
if is_center:
coord = obj_box_coord_centroid_to_upleft(coord)
##======= pixel unit format and upleft, w, h ==========##
x = coord[0] - ty # only change this
y = coord[1] - tx # only change this
w = coord[2]
h = coord[3]
if x < 0:
if x + w <= 0:
return None
w = w + x
x = 0
elif x > im_new.shape[1]: # object outside the cropped image
return None
if y < 0:
if y + h <= 0:
return None
h = h + y
y = 0
elif y > im_new.shape[0]: # object outside the cropped image
return None
if (x is not None) and (x + w > im_new.shape[1]): # box outside the cropped image
w = im_new.shape[1] - x
if (y is not None) and (y + h > im_new.shape[0]): # box outside the cropped image
h = im_new.shape[0] - y
if (w / (h + 1.) > thresh_wh2) or (h / (w + 1.) > thresh_wh2): # object shape strange: too narrow
# tl.logging.info('xx', w, h)
return None
if (w / (im_new.shape[1] * 1.) < thresh_wh) or (h / (im_new.shape[0] * 1.) <
thresh_wh): # object shape strange: too narrow
# tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0])
return None
coord = [x, y, w, h]
## convert back if input format is center.
if is_center:
coord = obj_box_coord_upleft_to_centroid(coord)
return coord
coords_new = list()
classes_new = list()
for i, _ in enumerate(coords):
coord = coords[i]
if len(coord) != 4:
raise AssertionError("coordinate should be 4 values : [x, y, w, h]")
if is_rescale:
# for scaled coord, upscaled before process and scale back in the end.
coord = obj_box_coord_scale_to_pixelunit(coord, im.shape)
coord = _get_coord(coord)
if coord is not None:
coord = obj_box_coord_rescale(coord, im_new.shape)
coords_new.append(coord)
classes_new.append(classes[i])
else:
coord = _get_coord(coord)
if coord is not None:
coords_new.append(coord)
classes_new.append(classes[i])
return im_new, classes_new, coords_new | [
"def",
"obj_box_shift",
"(",
"im",
",",
"classes",
"=",
"None",
",",
"coords",
"=",
"None",
",",
"wrg",
"=",
"0.1",
",",
"hrg",
"=",
"0.1",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
",",
"channel_index",
"=",
"2",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
",",
"order",
"=",
"1",
",",
"is_rescale",
"=",
"False",
",",
"is_center",
"=",
"False",
",",
"is_random",
"=",
"False",
",",
"thresh_wh",
"=",
"0.02",
",",
"thresh_wh2",
"=",
"12.",
")",
":",
"if",
"classes",
"is",
"None",
":",
"classes",
"=",
"[",
"]",
"if",
"coords",
"is",
"None",
":",
"coords",
"=",
"[",
"]",
"imh",
",",
"imw",
"=",
"im",
".",
"shape",
"[",
"row_index",
"]",
",",
"im",
".",
"shape",
"[",
"col_index",
"]",
"if",
"(",
"hrg",
">=",
"1.0",
")",
"and",
"(",
"hrg",
"<=",
"0.",
")",
"and",
"(",
"wrg",
">=",
"1.0",
")",
"and",
"(",
"wrg",
"<=",
"0.",
")",
":",
"raise",
"AssertionError",
"(",
"\"shift range should be (0, 1)\"",
")",
"if",
"is_random",
":",
"tx",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"hrg",
",",
"hrg",
")",
"*",
"imh",
"ty",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"wrg",
",",
"wrg",
")",
"*",
"imw",
"else",
":",
"tx",
",",
"ty",
"=",
"hrg",
"*",
"imh",
",",
"wrg",
"*",
"imw",
"translation_matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"tx",
"]",
",",
"[",
"0",
",",
"1",
",",
"ty",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"transform_matrix",
"=",
"translation_matrix",
"# no need to do offset",
"im_new",
"=",
"affine_transform",
"(",
"im",
",",
"transform_matrix",
",",
"channel_index",
",",
"fill_mode",
",",
"cval",
",",
"order",
")",
"# modified from obj_box_crop",
"def",
"_get_coord",
"(",
"coord",
")",
":",
"\"\"\"Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates,\n before getting the new coordinates.\n Boxes outsides the cropped image will be removed.\n\n \"\"\"",
"if",
"is_center",
":",
"coord",
"=",
"obj_box_coord_centroid_to_upleft",
"(",
"coord",
")",
"##======= pixel unit format and upleft, w, h ==========##",
"x",
"=",
"coord",
"[",
"0",
"]",
"-",
"ty",
"# only change this",
"y",
"=",
"coord",
"[",
"1",
"]",
"-",
"tx",
"# only change this",
"w",
"=",
"coord",
"[",
"2",
"]",
"h",
"=",
"coord",
"[",
"3",
"]",
"if",
"x",
"<",
"0",
":",
"if",
"x",
"+",
"w",
"<=",
"0",
":",
"return",
"None",
"w",
"=",
"w",
"+",
"x",
"x",
"=",
"0",
"elif",
"x",
">",
"im_new",
".",
"shape",
"[",
"1",
"]",
":",
"# object outside the cropped image",
"return",
"None",
"if",
"y",
"<",
"0",
":",
"if",
"y",
"+",
"h",
"<=",
"0",
":",
"return",
"None",
"h",
"=",
"h",
"+",
"y",
"y",
"=",
"0",
"elif",
"y",
">",
"im_new",
".",
"shape",
"[",
"0",
"]",
":",
"# object outside the cropped image",
"return",
"None",
"if",
"(",
"x",
"is",
"not",
"None",
")",
"and",
"(",
"x",
"+",
"w",
">",
"im_new",
".",
"shape",
"[",
"1",
"]",
")",
":",
"# box outside the cropped image",
"w",
"=",
"im_new",
".",
"shape",
"[",
"1",
"]",
"-",
"x",
"if",
"(",
"y",
"is",
"not",
"None",
")",
"and",
"(",
"y",
"+",
"h",
">",
"im_new",
".",
"shape",
"[",
"0",
"]",
")",
":",
"# box outside the cropped image",
"h",
"=",
"im_new",
".",
"shape",
"[",
"0",
"]",
"-",
"y",
"if",
"(",
"w",
"/",
"(",
"h",
"+",
"1.",
")",
">",
"thresh_wh2",
")",
"or",
"(",
"h",
"/",
"(",
"w",
"+",
"1.",
")",
">",
"thresh_wh2",
")",
":",
"# object shape strange: too narrow",
"# tl.logging.info('xx', w, h)",
"return",
"None",
"if",
"(",
"w",
"/",
"(",
"im_new",
".",
"shape",
"[",
"1",
"]",
"*",
"1.",
")",
"<",
"thresh_wh",
")",
"or",
"(",
"h",
"/",
"(",
"im_new",
".",
"shape",
"[",
"0",
"]",
"*",
"1.",
")",
"<",
"thresh_wh",
")",
":",
"# object shape strange: too narrow",
"# tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0])",
"return",
"None",
"coord",
"=",
"[",
"x",
",",
"y",
",",
"w",
",",
"h",
"]",
"## convert back if input format is center.",
"if",
"is_center",
":",
"coord",
"=",
"obj_box_coord_upleft_to_centroid",
"(",
"coord",
")",
"return",
"coord",
"coords_new",
"=",
"list",
"(",
")",
"classes_new",
"=",
"list",
"(",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"coords",
")",
":",
"coord",
"=",
"coords",
"[",
"i",
"]",
"if",
"len",
"(",
"coord",
")",
"!=",
"4",
":",
"raise",
"AssertionError",
"(",
"\"coordinate should be 4 values : [x, y, w, h]\"",
")",
"if",
"is_rescale",
":",
"# for scaled coord, upscaled before process and scale back in the end.",
"coord",
"=",
"obj_box_coord_scale_to_pixelunit",
"(",
"coord",
",",
"im",
".",
"shape",
")",
"coord",
"=",
"_get_coord",
"(",
"coord",
")",
"if",
"coord",
"is",
"not",
"None",
":",
"coord",
"=",
"obj_box_coord_rescale",
"(",
"coord",
",",
"im_new",
".",
"shape",
")",
"coords_new",
".",
"append",
"(",
"coord",
")",
"classes_new",
".",
"append",
"(",
"classes",
"[",
"i",
"]",
")",
"else",
":",
"coord",
"=",
"_get_coord",
"(",
"coord",
")",
"if",
"coord",
"is",
"not",
"None",
":",
"coords_new",
".",
"append",
"(",
"coord",
")",
"classes_new",
".",
"append",
"(",
"classes",
"[",
"i",
"]",
")",
"return",
"im_new",
",",
"classes_new",
",",
"coords_new"
] | Shift an image randomly or non-randomly, and compute the new bounding box coordinates.
Objects outside the cropped image will be removed.
Parameters
-----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
classes : list of int or None
Class IDs.
coords : list of list of 4 int/float or None
Coordinates [[x, y, w, h], [x, y, w, h], ...]
wrg, hrg row_index col_index channel_index is_random fill_mode cval and order : see ``tl.prepro.shift``.
is_rescale : boolean
Set to True, if the input coordinates are rescaled to [0, 1]. Default is False.
is_center : boolean
Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False.
thresh_wh : float
Threshold, remove the box if its ratio of width(height) to image size less than the threshold.
thresh_wh2 : float
Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold.
Returns
-------
numpy.array
A processed image
list of int
A list of classes
list of list of 4 numbers
A list of new bounding boxes. | [
"Shift",
"an",
"image",
"randomly",
"or",
"non",
"-",
"randomly",
"and",
"compute",
"the",
"new",
"bounding",
"box",
"coordinates",
".",
"Objects",
"outside",
"the",
"cropped",
"image",
"will",
"be",
"removed",
"."
] | aa9e52e36c7058a7e6fd81d36563ca6850b21956 | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L3012-L3144 | valid |