def main():
t = time.time()
img = imread(args.img_file_path)
imgs = [img, watermark(img), rotate(img), crop(img), mirror(img)]
imgs_norm = image_normalize(imgs)
dataset_features = np.load('fc6.npy')
query_start = time.time()
query_features = extract_feature(imgs_norm)
binarizer = preprocessing.Binarizer().fit(query_features)
query_features = binarizer.transform(query_features)
print(dataset_features)
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist
cosine = distance.cdist(dataset_features, query_features, 'cosine')
print(cosine.shape)
dis = cosine
inds_all = argsort(dis, axis=0) # ???? https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html
print('query cost: %f, dataset: %d, query: %d' % (time.time() - query_start, len(dataset_features), len(imgs)))
img_names = load_image_names()
fig, axes = plt.subplots(5, 11, figsize=(22, 10), subplot_kw={'xticks': [], 'yticks': []})
fig.subplots_adjust(hspace=0.15, wspace=0.01, left=.02, right=.98, top=.92, bottom=.08)
titles = ['original', 'watermark', 'rotate', 'crop', 'mirror']
for i in range(len(imgs)):
topK = []
inds = inds_all[:, i]
# print(inds)
for k in range(10):
topK.append(img_names[inds[k]])
print(inds[k], dis[inds[k], i], img_names[inds[k]])
original = axes[i, 0]
original.set_title(titles[i])
img = imgs[i]
original.imshow(img)
for j in range(10):
ax = axes[i, j + 1]
img = imread(topK[j])
ax.imshow(img)
title = '%d : %f' % (j + 1, dis[inds[j], i])
ax.set_title(title)
savePath = args.img_file_path + '_search_result.jpg'
plt.savefig(savePath)
print(time.time() - t)
# os.system('open -a Preview.app -F ' + savePath)
python类rotate()的实例源码
def get_batch_patches(img_clec, label_clec, patch_dim, batch_size, chn=1, flip_flag=True, rot_flag=True):
"""generate a batch of paired patches for training"""
batch_img = np.zeros([batch_size, patch_dim, patch_dim, patch_dim, chn]).astype('float32')
batch_label = np.zeros([batch_size, patch_dim, patch_dim, patch_dim]).astype('int32')
for k in range(batch_size):
# randomly select an image pair
rand_idx = np.arange(len(img_clec))
np.random.shuffle(rand_idx)
rand_img = img_clec[rand_idx[0]]
rand_label = label_clec[rand_idx[0]]
rand_img = rand_img.astype('float32')
rand_label = rand_label.astype('int32')
# randomly select a box anchor
l, w, h = rand_img.shape
l_rand = np.arange(l - patch_dim)
w_rand = np.arange(w - patch_dim)
h_rand = np.arange(h - patch_dim)
np.random.shuffle(l_rand)
np.random.shuffle(w_rand)
np.random.shuffle(h_rand)
pos = np.array([l_rand[0], w_rand[0], h_rand[0]])
# crop
img_temp = copy.deepcopy(rand_img[pos[0]:pos[0]+patch_dim, pos[1]:pos[1]+patch_dim, pos[2]:pos[2]+patch_dim])
# normalization
img_temp = img_temp/255.0
mean_temp = np.mean(img_temp)
dev_temp = np.std(img_temp)
img_norm = (img_temp - mean_temp) / dev_temp
label_temp = copy.deepcopy(rand_label[pos[0]:pos[0]+patch_dim, pos[1]:pos[1]+patch_dim, pos[2]:pos[2]+patch_dim])
# possible augmentation
# rotation
if rot_flag and np.random.random() > 0.65:
# print 'rotating patch...'
rand_angle = [-25, 25]
np.random.shuffle(rand_angle)
img_norm = rotate(img_norm, angle=rand_angle[0], axes=(1, 0), reshape=False, order=1)
label_temp = rotate(label_temp, angle=rand_angle[0], axes=(1, 0), reshape=False, order=0)
batch_img[k, :, :, :, chn-1] = img_norm
batch_label[k, :, :, :] = label_temp
return batch_img, batch_label
# calculate the cube information
def add_text_img(img, text, pos, box=None, color=None, thickness=1, scale=1, vertical=False):
"""
Adds the given text in the image.
:param img: Input image
:param text: String text
:param pos: (x, y) in the image or relative to the given Box object
:param box: Box object. If not None, the text is placed inside the box.
:param color: Color of the text.
:param thickness: Thickness of the font.
:param scale: Font size scale.
:param vertical: If true, the text is displayed vertically. (slow)
:return:
"""
if color is None:
color = COL_WHITE
text = str(text)
top_left = pos
if box is not None:
top_left = box.move(pos).to_int().top_left()
if top_left[0] > img.shape[1]:
return
if vertical:
if box is not None:
h, w, d = box.height, box.width, 3
else:
h, w, d = img.shape
txt_img = np.zeros((w, h, d), dtype=np.uint8)
# 90 deg rotation
top_left = h - pos[1], pos[0]
cv.putText(txt_img, text, top_left, cv.FONT_HERSHEY_PLAIN, scale, color, thickness)
txt_img = ndimage.rotate(txt_img, 90)
mask = txt_img > 0
if box is not None:
im_box = img_box(img, box)
im_box[mask] = txt_img[mask]
else:
img[mask] = txt_img[mask]
else:
cv.putText(img, text, top_left, cv.FONT_HERSHEY_PLAIN, scale, color, thickness)
def plot_overlays(atlas, b0, cmaps):
plt.rcParams.update({'axes.labelsize': 'x-large',
'axes.titlesize': 'x-large'})
if b0.shape == (182, 218, 182):
x = [78, 90, 100]
y = [82, 107, 142]
z = [88, 103, 107]
else:
shap = b0.shape
x = [int(shap[0]*0.35), int(shap[0]*0.51), int(shap[0]*0.65)]
y = [int(shap[1]*0.35), int(shap[1]*0.51), int(shap[1]*0.65)]
z = [int(shap[2]*0.35), int(shap[2]*0.51), int(shap[2]*0.65)]
coords = (x, y, z)
labs = ['Sagittal Slice (YZ fixed)',
'Coronal Slice (XZ fixed)',
'Axial Slice (XY fixed)']
var = ['X', 'Y', 'Z']
# create subplot for first slice
# and customize all labels
idx = 0
for i, coord in enumerate(coords):
for pos in coord:
idx += 1
ax = plt.subplot(3, 3, idx)
ax.set_title(var[i] + " = " + str(pos))
if i == 0:
image = ndimage.rotate(b0[pos, :, :], 90)
atl = ndimage.rotate(atlas[pos, :, :], 90)
elif i == 1:
image = ndimage.rotate(b0[:, pos, :], 90)
atl = ndimage.rotate(atlas[:, pos, :], 90)
else:
image = b0[:, :, pos]
atl = atlas[:, :, pos]
if idx % 3 == 1:
ax.set_ylabel(labs[i])
ax.yaxis.set_ticks([0, image.shape[0]/2, image.shape[0] - 1])
ax.xaxis.set_ticks([0, image.shape[1]/2, image.shape[1] - 1])
min_val, max_val = get_min_max(image)
plt.imshow(atl, interpolation='none', cmap=cmaps[0], alpha=0.5)
plt.imshow(image, interpolation='none', cmap=cmaps[1], alpha=0.5,
vmin=min_val, vmax=max_val)
fig = plt.gcf()
fig.set_size_inches(12.5, 10.5, forward=True)
return fig
def plot_rgb(im):
plt.rcParams.update({'axes.labelsize': 'x-large',
'axes.titlesize': 'x-large'})
if im.shape == (182, 218, 182):
x = [78, 90, 100]
y = [82, 107, 142]
z = [88, 103, 107]
else:
shap = im.shape
x = [int(shap[0]*0.35), int(shap[0]*0.51), int(shap[0]*0.65)]
y = [int(shap[1]*0.35), int(shap[1]*0.51), int(shap[1]*0.65)]
z = [int(shap[2]*0.35), int(shap[2]*0.51), int(shap[2]*0.65)]
coords = (x, y, z)
labs = ['Sagittal Slice (YZ fixed)',
'Coronal Slice (XZ fixed)',
'Axial Slice (XY fixed)']
var = ['X', 'Y', 'Z']
idx = 0
for i, coord in enumerate(coords):
for pos in coord:
idx += 1
ax = plt.subplot(3, 3, idx)
ax.set_title(var[i] + " = " + str(pos))
if i == 0:
image = ndimage.rotate(im[pos, :, :], 90)
elif i == 1:
image = ndimage.rotate(im[:, pos, :], 90)
else:
image = im[:, :, pos]
if idx % 3 == 1:
ax.set_ylabel(labs[i])
ax.yaxis.set_ticks([0, image.shape[0]/2, image.shape[0] - 1])
ax.xaxis.set_ticks([0, image.shape[1]/2, image.shape[1] - 1])
plt.imshow(image)
fig = plt.gcf()
fig.set_size_inches(12.5, 10.5, forward=True)
return fig