def load_image_array_flowers(image_file, image_size):
img = skimage.io.imread(image_file)
# GRAYSCALE
if len(img.shape) == 2:
img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8')
img_new[:,:,0] = img
img_new[:,:,1] = img
img_new[:,:,2] = img
img = img_new
img_resized = skimage.transform.resize(img, (image_size, image_size))
# FLIP HORIZONTAL WIRH A PROBABILITY 0.5
if random.random() > 0.5:
img_resized = np.fliplr(img_resized)
return img_resized.astype('float32')
python类io()的实例源码
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
# returns the top1 string
def load_image2(path, height=None, width=None):
# load image
img = skimage.io.imread(path)
img = img / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
def loadImg(fn,enc,dtype='float'):
"""Loads image from filename fn with encoding enc and returns it as with given dtype.
Args:
fn (str): File path.
enc (str): Image encoding, e.g. 'uint16'.
Keyword Args:
dtype (str): Datatype of pixels of returned image.
Returns:
numpy.ndarray: Loaded image.
"""
#Load image
img = skimage.io.imread(fn).astype(enc)
#Getting img values
img=img.real
img=img.astype(dtype)
return img
def flowList(xFileNames, yFileNames):
'''
(x/y)fileNames: List of the fileNames in order to get the flows from
'''
frameList = []
if (len(xFileNames) != len(yFileNames)):
print 'XFILE!=YFILE ERROR: In', xFileNames[0]
for i in range(0, min(len(xFileNames), len(yFileNames))):
imgX = io.imread(xFileNames[i])
imgY = io.imread(yFileNames[i])
frameList.append(np.dstack((imgX, imgY)))
frameList = np.array(frameList)
return frameList
def mandelbrot_color(matrix, output_file_name):
"""Generates a color version of the Mandelbrot Set
Writes its output file to output_file_name
Args:
matrix: np.array, 2D array representing the mandelbrot set
output_file_name: string, filename to write image to
"""
# I wasn't quite sure on how to do the coloring, so I just interpolated
# between two colors:
color1 = np.array([[.2], [.2], [.8]])
color2 = np.array([[1], [.2], [.5]])
color_img = np.zeros((matrix.shape[0], matrix.shape[1], 3))
color_img[:, :, 0] = color1[0] + matrix[:, :] * (color2[0] - color1[0])
color_img[:, :, 1] = color1[1] + matrix[:, :] * (color2[1] - color1[1])
color_img[:, :, 2] = color1[2] + matrix[:, :] * (color2[2] - color1[2])
print("\nWriting image to:", output_file_name)
skimage.io.imsave(output_file_name, color_img)
def write_img(out_img, out_filename, do_clip=True):
"""Writes out_img to out_filename
"""
if use_4channel and len(out_img.shape) == 3 and out_img.shape[2] == 4:
out_img = out_img[:,:,:3]
assert out_img is not None, 'expected out_img to not be None'
out_img = numpy.clip(out_img, 0, 1) if do_clip else out_img
if is_pypy:
out_img = numpy.asarray(out_img*255, 'uint8')
if len(out_img.shape) == 2:
mode = 'L'
elif len(out_img.shape) == 3:
if out_img.shape[2] == 3:
mode = 'RGB'
elif out_img.shape[2] == 4:
mode = 'RGBA'
else:
raise ValueError('unknown color image mode')
else:
raise ValueError('unknown number of dimensions for image')
I = Image.frombytes(mode, (out_img.shape[1], out_img.shape[0]), out_img.tobytes())
I.save(out_filename)
else:
try:
skimage.io.imsave(out_filename, out_img)
except:
print('Caught exception while saving to {}: image shape is {}, min: {}, max: {}'.format(out_filename, out_img.shape, out_img.min(), out_img.max()))
raise
def load_image2(path, height=None, width=None):
# load image
img = skimage.io.imread(path)
img = img / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
def load_image(path, size=224):
# 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, (size, size))
return resized_img
# returns the top1 string
def load_image2(path, height=None, width=None):
# load image
img = skimage.io.imread(path)
img = img / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
def load_image(path):
# Load image [height, width, depth]
img = skimage.io.imread(path) / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
# 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)
shape = list(img.shape)
crop_img = img[yy: yy + short_edge, xx: xx + short_edge]
resized_img = skimage.transform.resize(crop_img, (shape[0], shape[1]))
return resized_img, shape
# Return a resized numpy array of an image specified by its path
def load_image2(path, height=None, width=None):
# Load image
img = skimage.io.imread(path) / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
# Render the generated image given a tensorflow session and a variable image (x)
def load_image2(path, height=None, width=None):
# load image
img = skimage.io.imread(path)
img = img / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
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))
if len(resized_img.shape)<3:
resized_img = skimage.color.gray2rgb(resized_img)
return resized_img
# returns the top1 string
def load_image2(path, height=None, width=None):
# load image
img = skimage.io.imread(path)
img = img / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
def load_image(path):
# Load image [height, width, depth]
img = skimage.io.imread(path) / 255.0
assert (0 <= img).all() and (img <= 1.0).all()
# 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)
shape = list(img.shape)
crop_img = img[yy: yy + short_edge, xx: xx + short_edge]
resized_img = skimage.transform.resize(crop_img, (shape[0], shape[1]))
return resized_img, shape
# Return a resized numpy array of an image specified by its path
def load_image2(path, height=None, width=None):
# Load image
img = skimage.io.imread(path) / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
# Render the generated image given a tensorflow session and a variable image (x)
def load_image_array(image_file, image_size):
img = skimage.io.imread(image_file)
# GRAYSCALE
if len(img.shape) == 2:
img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8')
img_new[:,:,0] = img
img_new[:,:,1] = img
img_new[:,:,2] = img
img = img_new
img_resized = skimage.transform.resize(img, (image_size, image_size))
# FLIP HORIZONTAL WIRH A PROBABILITY 0.5
if random.random() > 0.5:
img_resized = np.fliplr(img_resized)
return img_resized.astype('float32')
def load_image(path, height=None, width=None):
img = skimage.io.imread(path)
if len(img.shape) == 2:
img = skimage.color.gray2rgb(img)
img = img / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
def imread(path):
return skimage.io.imread(path)
def imwrite(im, path):
skimage.io.imsave(path, im)
def load_image_array(image_file, image_size,
image_id, data_dir='Data/datasets/mscoco/train2014',
mode='train'):
img = None
if os.path.exists(image_file):
#print('found' + image_file)
img = skimage.io.imread(image_file)
else:
print('notfound' + image_file)
img = skimage.io.imread('http://mscoco.org/images/%d' % (image_id))
img_path = os.path.join(data_dir, 'COCO_%s2014_%.12d.jpg' % ( mode,
image_id))
skimage.io.imsave(img_path, img)
# GRAYSCALE
if len(img.shape) == 2:
img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8')
img_new[:,:,0] = img
img_new[:,:,1] = img
img_new[:,:,2] = img
img = img_new
img_resized = skimage.transform.resize(img, (image_size, image_size))
# FLIP HORIZONTAL WIRH A PROBABILITY 0.5
if random.random() > 0.5:
img_resized = np.fliplr(img_resized)
return img_resized.astype('float32')
def load_image_inception(image_file, image_size=128):
img = skimage.io.imread(image_file)
# GRAYSCALE
if len(img.shape) == 2:
img_new = np.ndarray((img.shape[0], img.shape[1], 3), dtype='uint8')
img_new[:, :, 0] = img
img_new[:, :, 1] = img
img_new[:, :, 2] = img
img = img_new
if image_size != 0:
img = skimage.transform.resize(img, (image_size, image_size), mode='reflect')
return img.astype('int32')
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 saveImg(img,fn,enc="uint16",scale=True,maxVal=None):
"""Saves image as tif file.
``scale`` triggers the image to be scaled to either the maximum
range of encoding or ``maxVal``. See also :py:func:`scaleToEnc`.
Args:
img (numpy.ndarray): Image to save.
fn (str): Filename.
Keyword Args:
enc (str): Encoding of image.
scale (bool): Scale image.
maxVal (int): Maximum value to which image is scaled.
Returns:
str: Filename.
"""
#Fill nan pixels with 0
img=np.nan_to_num(img)
#Scale img
if scale:
img=scaleToEnc(img,enc,maxVal=maxVal)
else:
#Convert to encoding
img=img.astype(enc)
skimage.io.imsave(fn,img)
return fn
def check_files(image_dir):
print("Checking image files in %s" %(image_dir))
files = os.listdir(image_dir)
images = [os.path.join(image_dir, f) for f in files if f.lower().endswith('.jpg')]
good_imgs = []
for img in images:
try:
x = skimage.img_as_float(skimage.io.imread(img)).astype(np.float32)
good_imgs.append(img)
except:
print("Image %s is corrupted and will be removed." %(img))
os.remove(img)
good_files = [img.split(os.sep)[-1] for img in good_imgs]
return good_files
def __init__(self, deploy=vgg_deploy, model=vgg_model, mean=vgg_mean, scale_dim=[224, 224], image_dim=[224, 224], isotropic=False):
caffe.set_mode_gpu()
caffe.Net.__init__(self, deploy, model, caffe.TEST)
self.scale_dim = np.array(scale_dim)
self.image_dim = np.array(image_dim)
self.isotropic = isotropic
self.transformer = caffe.io.Transformer({'data':self.blobs['data'].data.shape})
self.transformer.set_transpose('data', (2,0,1))
self.transformer.set_mean('data', np.load(mean).mean(1).mean(1))
self.transformer.set_raw_scale('data', 255)
self.transformer.set_channel_swap('data', (2,1,0))
def load_image(self, image_dir):
image = skimage.img_as_float(skimage.io.imread(image_dir)).astype(np.float32)
assert image.ndim == 2 or image.ndim == 3
if image.ndim == 2:
image = image[:, :, np.newaxis]
image = np.tile(image, (1, 1, 3))
elif image.shape[2] > 3:
image = image[:, :, :3]
return image
def mandelbrot_gray(matrix, output_file_name):
"""Generates a grayscale version of the Mandelbrot Set
Writes its output file to output_file_name
Args:
matrix: np.array, 2D array representing the mandelbrot set
output_file_name: string, filename to write image to
"""
print("\nWriting image to:", output_file_name)
skimage.io.imsave(output_file_name, matrix)
def read_img(in_filename, grayscale=False, extra_info={}):
"""Returns the image saved at in_filename as a numpy array.
If grayscale is True, converts from 3D RGB image to 2D grayscale image.
"""
if is_pypy:
ans = Image.open(in_filename)
height = ans.height
width = ans.width
channels = len(ans.getbands())
if ans.mode == 'I':
numpy_mode = 'uint32'
maxval = 65535.0
elif ans.mode in ['L', 'RGB', 'RGBA']:
numpy_mode = 'uint8'
maxval = 255.0
else:
raise ValueError('unknown mode')
ans = numpy.fromstring(ans.tobytes(), numpy_mode).reshape((height, width, channels))
ans = ans/maxval
if grayscale and (len(ans.shape) == 3 and ans.shape[2] == 3):
ans = ans[:,:,0]*0.2125 + ans[:,:,1]*0.7154 + ans[:,:,2]*0.0721
if len(ans.shape) == 3 and ans.shape[2] == 1:
ans = ans[:,:,0]
return ans
else:
ans = skimage.io.imread(in_filename)
if ans.dtype == numpy.int32: # Work around scikit-image bug #1680
ans = numpy.asarray(ans, numpy.uint16)
ans = skimage.img_as_float(ans)
if grayscale:
ans = skimage.color.rgb2gray(ans)
# print('here', use_4channel, len(ans.shape) == 3, ans.shape[2] == 3)
if use_4channel and len(ans.shape) == 3 and ans.shape[2] == 3:
ans = numpy.dstack((ans,) + (numpy.ones((ans.shape[0], ans.shape[1], 1)),))
extra_info['originally_3channel'] = True
return ans