def __enter__(self):
if not self.verbose:
self.old_stdout = sys.stdout
self.old_stderr = sys.stderr
sys.stdout = self.stdout = io.StringIO()
sys.stderr = self.stderr = io.StringIO()
python类io()的实例源码
def load_images(image_files, vgg, pl_images):
dataset = np.ndarray(shape=(len(image_files), feat_len), dtype=np.float32)
image_index = 0
for image in image_files:
try:
if not tf.gfile.Exists(image):
tf.logging.fatal('File does not exist %s', image)
image_data = skimage.io.imread(image)
image_data = image_data / 255.0
batch = np.ndarray(shape=(1, image_data.shape[0], image_data.shape[1], image_data.shape[2]), dtype=np.float32)
batch[0, :, :, :] = image_data
feed_dict = {pl_images: batch}
with tf.Session() as sess:
with tf.device("/cpu:0"):
feat = sess.run(vgg.conv5_4, feed_dict=feed_dict)
feat.resize(feat_len,refcheck=False)
dataset[image_index, :] = feat
image_index += 1
except IOError as e:
print('Could not read:', image, ':', e, '- it\'s ok, skipping.')
dataset = dataset[0:image_index, :]
print('Full dataset tensor:', dataset.shape)
return dataset
def load_image(path, image_h, image_w, zoom=False):
# load image
img = skimage.io.imread(path)
if img.ndim < 3:
img = skimage.color.gray2rgb(img)
# we crop image from center
ratio = float(image_h) / image_w
height = int(img.shape[0])
width = int(img.shape[1])
yy = 0
xx = 0
if height > width * ratio: #too tall
yy = int(height - width * ratio) // 2
height = int(width * ratio)
else: # too wide
xx = int(width - height / ratio) // 2
width = int(height / ratio)
if zoom:
yy += int(height / 6)
xx += int(height / 6)
height = int(height * 2/ 3)
width = int(width * 2 / 3)
crop_img = img[yy: yy + height, xx: xx + width]
# resize
resized_img = skimage.transform.resize(crop_img, (image_h, image_w), preserve_range=True)
centered_img = resized_img - MEAN_VALUES
return centered_img
def write_image(path, image, verbose=False):
img = image[0] + MEAN_VALUES
if verbose:
print("%f - %f" % (np.min(img), np.max(img)))
img = np.clip(img, 0, 255).astype('uint8')
skimage.io.imsave(path, img)
# returns the top1 string
def test():
img = skimage.io.imread("./test_data/starry_night.jpg")
ny = 300
nx = img.shape[1] * ny / img.shape[0]
img = skimage.transform.resize(img, (ny, nx))
skimage.io.imsave("./test_data/test/output.jpg", img)
def get_all_test_data(im_list, la_list):
images = []
labels = []
index = 0
for im_filename, la_filename in zip(im_list, la_list):
im = np.array(skimage.io.imread(im_filename), np.float32)
im = im[np.newaxis]
la = skimage.io.imread(la_filename)
la = la[np.newaxis]
la = la[...,np.newaxis]
images.append(im)
labels.append(la)
return images, labels
def imread(path):
return skimage.io.imread(path)
def imwrite(im, path):
skimage.io.imsave(path, im)
def test():
img = skimage.io.imread("./test_data/starry_night.jpg")
ny = 300
nx = img.shape[1] * ny / img.shape[0]
img = skimage.transform.resize(img, (ny, nx))
skimage.io.imsave("./test_data/test/output.jpg", img)
tutorial_inceptionV3_tfslim.py 文件源码
项目:tensorlayer-chinese
作者: shorxp
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def load_image(path):
# load image
img = skimage.io.imread(path)
img = img / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
# print "Original Image Shape: ", img.shape
# we crop image from center
short_edge = min(img.shape[:2])
yy = int((img.shape[0] - short_edge) / 2)
xx = int((img.shape[1] - short_edge) / 2)
crop_img = img[yy: yy + short_edge, xx: xx + short_edge]
# resize to 299, 299
resized_img = skimage.transform.resize(crop_img, (299, 299))
return resized_img
def load_image(path):
# load image
img = skimage.io.imread(path)
img = img / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
# print "Original Image Shape: ", img.shape
# we crop image from center
short_edge = min(img.shape[:2])
yy = int((img.shape[0] - short_edge) / 2)
xx = int((img.shape[1] - short_edge) / 2)
crop_img = img[yy: yy + short_edge, xx: xx + short_edge]
# resize to 224, 224
resized_img = skimage.transform.resize(crop_img, (224, 224))
return resized_img
tutorial_inceptionV3_tfslim.py 文件源码
项目:tensorlayer-chinese
作者: shorxp
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def load_image(path):
# load image
img = skimage.io.imread(path)
img = img / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
# print "Original Image Shape: ", img.shape
# we crop image from center
short_edge = min(img.shape[:2])
yy = int((img.shape[0] - short_edge) / 2)
xx = int((img.shape[1] - short_edge) / 2)
crop_img = img[yy: yy + short_edge, xx: xx + short_edge]
# resize to 224, 224
resized_img = skimage.transform.resize(crop_img, (299, 299))
return resized_img
def load_image(path):
# load image
img = skimage.io.imread(path)
img = img / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
# print "Original Image Shape: ", img.shape
# we crop image from center
short_edge = min(img.shape[:2])
yy = int((img.shape[0] - short_edge) / 2)
xx = int((img.shape[1] - short_edge) / 2)
crop_img = img[yy: yy + short_edge, xx: xx + short_edge]
# resize to 224, 224
resized_img = skimage.transform.resize(crop_img, (224, 224))
return resized_img
def get_saliency_ft(img):
# Saliency map calculation based on:
if isinstance(img, str):
img = skimage.io.imread(img)
img_rgb = img_as_float(img)
img_lab = skimage.color.rgb2lab(img_rgb)
mean_val = np.mean(img_rgb, axis=(0, 1))
kernel_h = (1.0 / 16.0) * np.array([[1, 4, 6, 4, 1]])
kernel_w = kernel_h.transpose()
blurred_l = scipy.signal.convolve2d(img_lab[:, :, 0], kernel_h, mode='same')
blurred_a = scipy.signal.convolve2d(img_lab[:, :, 1], kernel_h, mode='same')
blurred_b = scipy.signal.convolve2d(img_lab[:, :, 2], kernel_h, mode='same')
blurred_l = scipy.signal.convolve2d(blurred_l, kernel_w, mode='same')
blurred_a = scipy.signal.convolve2d(blurred_a, kernel_w, mode='same')
blurred_b = scipy.signal.convolve2d(blurred_b, kernel_w, mode='same')
im_blurred = np.dstack([blurred_l, blurred_a, blurred_b])
sal = np.linalg.norm(mean_val - im_blurred, axis=2)
sal_max = np.max(sal)
sal_min = np.min(sal)
sal = 255 * ((sal - sal_min) / (sal_max - sal_min))
return sal
def get_all_test_data(im_list, la_list):
images = []
labels = []
index = 0
for im_filename, la_filename in zip(im_list, la_list):
im = np.array(skimage.io.imread(im_filename), np.float32)
im = im[np.newaxis]
la = skimage.io.imread(la_filename)
la = la[np.newaxis]
la = la[...,np.newaxis]
images.append(im)
labels.append(la)
return images, labels
def test():
img = skimage.io.imread("./test_data/starry_night.jpg")
ny = 300
nx = img.shape[1] * ny / img.shape[0]
img = skimage.transform.resize(img, (ny, nx))
skimage.io.imsave("./test_data/test/output.jpg", img)
def saveLastBatchResults(self, outputImages, isTrain=True):
"""Saves the results of last retrieved image batch
Args:
outputImages: 4D Numpy array [batchSize, H, W, numClasses]
isTrain: If the last batch was training batch
Returns:
None
"""
if isTrain:
imageNames = [self.imageList[index] for index in self.indices]
else:
imageNames = [self.imageListTest[index] for index in self.indices]
# Iterate over each image name and save the results
for i in xrange(0, self.options.batchSize):
imageName = imageNames[i].split('/')
imageName = imageName[-1]
if isTrain:
imageName = self.options.imagesOutputDirectory + '/' + 'train_' + imageName[:-4] + '_prob' + imageName[-4:]
else:
imageName = self.options.imagesOutputDirectory + '/' + 'test_' + imageName[:-4] + '_prob' + imageName[-4:]
# print(imageName)
# Save foreground probability
im = np.squeeze(outputImages[i, :, :, 1] * 255)
im = im.astype(np.uint8) # Convert image from float to unit8 for saving
skimage.io.imsave(imageName, im)
data_loader.py 文件源码
项目:visual-question-answering-tensorflow
作者: lmelvix
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def getImage(datapath, imageID, purpose='train'):
name_3 = str(imageID)
name_2 = '0' * (12-len(name_3))
name_1 = 'COCO_' + purpose + '2014_'
fileName = name_1 + name_2 + name_3 + '.jpg'
filepath = join(datapath,fileName)
img = skimage.io.imread(filepath)
return(img)
def show_image(img):
skimage.io.imshow(img)
skimage.io.show()
# [height, width, depth]
def load_image(path):
# load image
img = skimage.io.imread(path)
img = img / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
print( "Original Image Shape: ", img.shape)
# we crop image from center
short_edge = min(img.shape[:2])
yy = int((img.shape[0] - short_edge) / 2)
xx = int((img.shape[1] - short_edge) / 2)
crop_img = img[yy: yy + short_edge, xx: xx + short_edge]
# resize to 224, 224
resized_img = skimage.transform.resize(crop_img, (256, 256))
print( "Resize Image Shape: ", resized_img.shape)
return resized_img