def load_mask(mask_path, shape):
mask = imread(mask_path, mode="L") # Grayscale mask load
width, height, _ = shape
mask = imresize(mask, (width, height), interp='bicubic').astype('float32')
# Perform binarization of mask
mask[mask <= 127] = 0
mask[mask > 128] = 255
max = np.amax(mask)
mask /= max
return mask
# util function to apply mask to generated image
python类imread()的实例源码
def preprocess_image(image_path, load_dims=False, style_image=False):
global img_WIDTH, img_HEIGHT, aspect_ratio, b_scale_ratio_height, b_scale_ratio_width
img = imread(image_path, mode="RGB") # Prevents crashes due to PNG images (ARGB)
if load_dims:
img_WIDTH = img.shape[0]
img_HEIGHT = img.shape[1]
aspect_ratio = img_HEIGHT / img_WIDTH
if style_image:
b_scale_ratio_width = float(img.shape[0]) / img_WIDTH
b_scale_ratio_height = float(img.shape[1]) / img_HEIGHT
img = imresize(img, (img_width, img_height))
img = img.transpose((2, 0, 1)).astype('float64')
img = np.expand_dims(img, axis=0)
return img
# util function to convert a tensor into a valid image
def load_test_data(phone, dped_dir, IMAGE_SIZE):
test_directory_phone = dped_dir + str(phone) + '/test_data/patches/' + str(phone) + '/'
test_directory_dslr = dped_dir + str(phone) + '/test_data/patches/canon/'
NUM_TEST_IMAGES = len([name for name in os.listdir(test_directory_phone)
if os.path.isfile(os.path.join(test_directory_phone, name))])
test_data = np.zeros((NUM_TEST_IMAGES, IMAGE_SIZE))
test_answ = np.zeros((NUM_TEST_IMAGES, IMAGE_SIZE))
for i in range(0, NUM_TEST_IMAGES):
I = np.asarray(misc.imread(test_directory_phone + str(i) + '.jpg'))
I = np.float16(np.reshape(I, [1, IMAGE_SIZE]))/255
test_data[i, :] = I
I = np.asarray(misc.imread(test_directory_dslr + str(i) + '.jpg'))
I = np.float16(np.reshape(I, [1, IMAGE_SIZE]))/255
test_answ[i, :] = I
if i % 100 == 0:
print(str(round(i * 100 / NUM_TEST_IMAGES)) + "% done", end="\r")
return test_data, test_answ
def predict():
# get data from drawing canvas and save as image
parseImage(request.get_data())
# read parsed image back in 8-bit, black and white mode (L)
x = imread('output.png', mode='L')
x = np.invert(x)
x = imresize(x,(28,28))
# reshape image data for use in neural network
x = x.reshape(1,28,28,1)
with graph.as_default():
out = model.predict(x)
print(out)
print(np.argmax(out, axis=1))
response = np.array_str(np.argmax(out, axis=1))
return response
def process_mot(path):
'''
1920 x 1080 -> 384 x 216
640 x 480 -> 320 x 240
'''
images = []
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename[-4:] == ".jpg" and "_ds" not in filename:
full_path = os.path.join(dirpath, filename)
img = misc.imread(full_path,mode='RGB')
if img.shape == LARGE_IMAGE_SIZE:
img = misc.imresize(img, size=LARGE_IMAGE_RESCALE)
img = pad_image(img, FINAL_IMAGE_SIZE)
elif img.shape == MEDIUM_IMAGE_SIZE:
img = misc.imresize(img, size=MEDIUM_IMAGE_RESCALE)
img = pad_image(img, FINAL_IMAGE_SIZE)
else:
print("Unexpected shape " + str(img.shape))
continue
output_filename = os.path.join(dirpath, filename[:-4] + "_ds.jpg")
misc.imsave(output_filename, img)
images.append(output_filename)
return images
def process_vot(path, min_height, min_width):
images = []
for dirpath, dirnames, filenames in os.walk(path):
img_shape = None
pad_height = 0
pad_width = 0
for filename in filenames:
if filename[-4:] == ".jpg" and "_ds" not in filename:
full_path = os.path.join(dirpath, filename)
img = misc.imread(full_path,mode='RGB')
img_shape = img.shape
ratio = min(float(min_width)/img.shape[1], float(min_height)/img.shape[0])
img = misc.imresize(img, size=ratio)
img, pad_height, pad_width = pad_image(img, (min_height, min_width))
output_filename = os.path.join(dirpath, filename[:-4] + "_ds.jpg")
misc.imsave(output_filename, img)
images.append(output_filename)
if img_shape:
gt_path = os.path.join(dirpath, "groundtruth.txt")
preprocess_label(gt_path, ratio, img_shape, min_height, min_width, pad_height, pad_width)
return images
def do_roc(self):
if self.gan_mode and self.dmodel2 is not None:
dmodel_cur = self.dmodel2
scale_factor = 2
elif self.dmodel is not None:
dmodel_cur = self.dmodel
scale_factor = self.scale_factor
else:
theApp.cur_hist_tex = theApp.standard_hist_tex
theApp.cur_roc_tex = theApp.standard_roc_tex
return
encoded_vector_source = self.get_encoded(dmodel_cur, self.cur_vector_source, scale_factor)
encoded_vector_dest = self.get_encoded(dmodel_cur, self.cur_vector_dest, scale_factor)
attribute_vector = encoded_vector_dest - encoded_vector_source
threshold = None
outfile = "{}/{}".format(roc_dir, get_date_str())
do_roc(attribute_vector, encoded, attribs, attribute_index, threshold, outfile)
hist_img = imread("{}_hist_both.png".format(outfile), mode='RGB')
roc_img = imread("{}_roc.png".format(outfile), mode='RGB')
hist_img = imresize(hist_img, roc_image_resize)
roc_img = imresize(roc_img, roc_image_resize)
theApp.cur_hist_tex = image_to_texture(hist_img)
theApp.cur_roc_tex = image_to_texture(roc_img)
def save_images(img_dir, dest_file):
img_list = os.listdir(img_dir)
img_combo = []
print('starting to save ' + str(len(img_list)) + ' images')
count = 0
for img_name in img_list:
# can change this line to img_name.startswith('center') for center imgs
if not img_name.startswith('.'):
if count % 500 == 0:
print('count is', count)
img = misc.imread(img_dir + '/' + img_name)
img_combo.append(img)
count += 1
#cast to numpy array and save to file
all_images = np.array(img_combo)
print('images shape', all_images.shape)
np.save(dest_file, all_images)
def show_file_images(filename, img_list):
fig = plt.figure()
#for 9 random images, print them
for img_num in range(0, 9):
random_num = random.randint(0, len(img_list))
img_name = img_list[random_num]
print('image name is ', img_name)
img = misc.imread(filename + img_name)
np_img = np.array(img)
flipped_img = np.fliplr(np_img)[60:160]
# print('img is ', img)
img = img[60:160]
fig.add_subplot(5, 5, img_num * 2 + 1)
plt.imshow(img)
fig.add_subplot(5, 5, img_num * 2 + 2)
plt.imshow(flipped_img)
plt.show()
def count_images(img_dir):
#add each to img_combo
img_list = os.listdir(img_dir)
l_count = 0
c_count = 0
r_count =0
for img_name in img_list:
if img_name.startswith('center'):
c_count += 1
elif img_name.startswith('left'):
l_count += 1
elif img_name.startswith('right'):
r_count +=1
# img = misc.imread(img_dir + '/' + img_name)
# img_combo.append(img)
print('counts l, c, r:', l_count, c_count, r_count)
def get_images_from_request(request_file, names):
"""get pillow images from flask request
@input: request_file: request.files
@input: names: image name list for read
@output: type ndarray. The array obtained by reading the image.
"""
img_list = []
for name in names:
# get upload file
f = request_file.get(name)
if f is None:
continue
img = misc.imread(f)
img_list.append(img)
return img_list
def view_(_pred,_lable):
fname = ['Captcha/lv3/%i.jpg' %i for i in range(20)]
img = []
for fn in fname:
img.append(Image.open(open(fn)))
#img.append(misc.imread(fn).astype(np.float))
for i in range(len(img)):
pylab.subplot(4,5,i+1); pylab.axis('off')
pylab.imshow(img[i])
#pylab.imshow( np.dot(np.array(img[i])[...,:3],[0.299,0.587,0.114]) , cmap=plt.get_cmap("gray"))
#pylab.text(40,60,_pred[i],color = 'b')
if ( _pred[i] == _lable[i] ):
pylab.text(40,65,_pred[i],color = 'b',size = 15)
else:
pylab.text(40,65,_pred[i],color = 'r',size = 15)
pylab.text(40,92,_lable[i],color = 'g',size = 15)
pylab.show()
def get_batch(generator_type, set_type, height, width):
imgs = []
if set_type == 'train' or set_type == 'val':
for paths, bbs, labels in generator_type:
for i in range(len(paths)):
img = gray2rgb(misc.imread(paths[i]), paths[i])
img = img[bbs[i][1]:bbs[i][1]+bbs[i][3], bbs[i][0]:bbs[i][0]+bbs[i][2],:]
img = preprocess_image(img, height, width, set_type)
imgs.append(img)
imgs = np.asarray(imgs)
break
return imgs, labels
else:
for paths, bbs in generator_type:
for i in range(len(paths)):
img = gray2rgb(misc.imread(paths[i]), paths[i])
img = img[bbs[i][1]:bbs[i][1]+bbs[i][3], bbs[i][0]:bbs[i][0]+bbs[i][2],:]
imgs.append(preprocess_image(img, height, width, set_type))
imgs = np.asarray(imgs)
break
return imgs, None
#store in required csv format
def get_img(data_path):
# Getting image array from path:
img = imread(data_path)
img = imresize(img, (64, 64))
return img
def readimg(img_path):
img = misc.imread(img_path, mode='RGB')
img = misc.imresize(img, (160, 160))
img = facenet.prewhiten(img)
img = np.expand_dims(img, axis=0)
return img
def get_embedding(img_path):
img = misc.imread(img_path, mode='RGB')
# judge alignment
aligned = align.align(160, img, [0, 0, img.shape[1], img.shape[0]], landmarkIndices=landmarkIndices)
img = facenet.prewhiten(img)
img = np.expand_dims(img, axis=0)
aligned = facenet.prewhiten(aligned)
aligned = np.expand_dims(aligned, axis=0)
# Run forward pass to calculate embeddings
feed_dict = {images_placeholder: img, phase_train_placeholder: False}
emb = sess.run(embeddings, feed_dict=feed_dict)
# Run forward pass to calculate embeddings
feed_dict_aligned = {images_placeholder: aligned, phase_train_placeholder: False}
emb_aligned = sess.run(embeddings, feed_dict=feed_dict_aligned)
return emb.ravel(), emb_aligned.ravel()
# # for test
# import os
# from time import time
# def main(dir_path):
# img_all = os.listdir(dir_path)
# for f in img_all:
# start = time()
# embedding_result = get_embedding(os.path.join(dir_path, f))
# print time() - start
# print embedding_result
#
# main('./data')
def load_data(image_paths, do_random_crop, do_random_flip, image_size, do_prewhiten=True):
nrof_samples = len(image_paths)
images = np.zeros((nrof_samples, image_size, image_size, 3))
for i in range(nrof_samples):
img = misc.imread(image_paths[i])
if img.ndim == 2:
img = to_rgb(img)
if do_prewhiten:
img = prewhiten(img)
img = crop(img, do_random_crop, image_size)
img = flip(img, do_random_flip)
images[i,:,:,:] = img
return images
def load_image(img_file_path):
img = imread(img_file_path)
img = (imresize(img, (227, 227))[:, :, :3]).astype(float32)
img = img - mean(img)
return img
def load_images(image_names):
imgs = []
for img_name in image_names:
img = imread(img_name)
img = (imresize(img, (227, 227))[:, :, :3]).astype(float32)
img = img - mean(img)
imgs.append(img)
return imgs
def main():
img = imread(args.input_path)
img = ndimage.rotate(img, args.angle, mode=args.mode)
misc.imsave(args.output_path, img)