def my_label2rgboverlay(labels, colors, image, alpha=0.2):
"""
Generates image with segmentation labels on top
Parameters
----------
labels: labels of one image (0, 1)
colors: colormap
image: image (0, 1, c), where c=3 (rgb)
alpha: transparency
"""
image_float = gray2rgb(img_as_float(rgb2gray(image) if
image.shape[2] == 3 else
np.squeeze(image)))
label_image = my_label2rgb(labels, colors)
output = image_float * alpha + label_image * (1 - alpha)
return output
python类img_as_float()的实例源码
def preprocess_frame(image, target_height=224, target_width=224):
if len(image.shape) == 2:
image = np.tile(image[:,:,None], 3)
elif len(image.shape) == 4:
image = image[:,:,:,0]
image = skimage.img_as_float(image).astype(np.float32)
height, width, rgb = image.shape
if width == height:
resized_image = cv2.resize(image, (target_height,target_width))
elif height < width:
resized_image = cv2.resize(image, (int(width * float(target_height)/height), target_width))
cropping_length = int((resized_image.shape[1] - target_height) / 2)
resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]
else:
resized_image = cv2.resize(image, (target_height, int(height * float(target_width) / width)))
cropping_length = int((resized_image.shape[0] - target_width) / 2)
resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]
return cv2.resize(resized_image, (target_height, target_width))
def process_patches(images, net, transformer):
""" Process a patch through the neural network and extract the predictions
Args:
images (array list): list of images to process (length = batch_size)
net (obj): the Caffe Net
transformer (obj): the Caffe Transformer for preprocessing
"""
# caffe.io.load_image converts to [0,1], so our transformer sets it back to [0,255]
# but the skimage lib already works with [0, 255] so we convert it to float with img_as_float
data = np.zeros(net.blobs['data'].data.shape)
for i in range(len(images)):
data[i] = transformer.preprocess('data', img_as_float(images[i]))
net.forward(data=data)
output = net.blobs['conv1_1_D'].data[:len(images)]
output = np.swapaxes(np.swapaxes(output, 1, 3), 1, 2)
return output
def process_patches(images, net, transformer):
""" Process a patch through the neural network and extract the predictions
Args:
images (array list): list of images to process (length = batch_size)
net (obj): the Caffe Net
transformer (obj): the Caffe Transformer for preprocessing
"""
# caffe.io.load_image converts to [0,1], so our transformer sets it back to [0,255]
# but the skimage lib already works with [0, 255] so we convert it to float with img_as_float
data = np.zeros(net.blobs['data'].data.shape)
for i in range(len(images)):
data[i] = transformer.preprocess('data', img_as_float(images[i]))
net.forward(data=data)
output = net.blobs['conv1_1_D'].data[:len(images)]
output = np.swapaxes(np.swapaxes(output, 1, 3), 1, 2)
return output
def load_img(self, img_filename):
"""
Summary:
Load image from the filename. Default is to load in color if
possible.
Args:
img_name (string): string of the image name, relative to
the image directory.
Returns:
np array of float32: an image as a numpy array of float32
"""
if not img_filename.endswith('.jpg'):
img_filename = os.path.join(self.img_dir, img_filename + '.jpg')
else:
img_filename = os.path.join(self.img_dir, img_filename)
img = skimage.img_as_float(io.imread(
img_filename)).astype(np.float32)
if img.ndim == 2:
img = img[:, :, np.newaxis]
elif img.shape[2] == 4:
img = img[:, :, :3]
return img
def crop_image(x, target_height=227, target_width=227):
image = skimage.img_as_float(skimage.io.imread(x)).astype(np.float32)
if len(image.shape) == 2:
image = np.tile(image[:,:,None], 3)
elif len(image.shape) == 4:
image = image[:,:,:,0]
height, width, rgb = image.shape
if width == height:
resized_image = skimage.transform.resize(image, (target_height,target_width))
elif height < width:
resized_image = skimage.transform.resize(image, (int(width * float(target_height)/height), target_width))
cropping_length = int((resized_image.shape[1] - target_height) / 2)
resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]
else:
resized_image = skimage.transform.resize(image, (target_height, int(height * float(target_width) / width)))
cropping_length = int((resized_image.shape[0] - target_width) / 2)
resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]
return skimage.transform.resize(resized_image, (target_height, target_width))
def postprocess(imgs, size, grayscale=False):
print("Postprocessing images and resize (at %d)" % size)
keyname = ('gray_%d' if grayscale else 'color_%d') % size
for img in imgs:
# Continue if already calculated
if img.isSetByName(keyname):
continue
floatimg = img_as_float(img.image)
floatimg = resize(floatimg, (size, size))
if grayscale:
floatimg = rgb2gray(floatimg)
img.setByName(keyname, floatimg) # expect to return floats
# Augment images
def load_data(src,shuffle=True):
""" Load data from directories.
"""
imgs = [img for img in glob.glob(os.path.join(src,'*.png'))]
x = np.zeros((len(imgs),100,100), dtype=np.float32)
y = np.zeros(len(imgs), dtype=np.int64)
for idx, img in enumerate(imgs):
im = io.imread(img,1)
im = img_as_float(im) # rescale from [0,255] to [0,1]
label = int(img.split('/')[-1].split('.')[0].split('_')[-1])
x[idx] = im
y[idx] = label
x = np.expand_dims(x,3)
data = zip(x,y)
if shuffle: random.shuffle(data)
return data
def predict_image(self, test_img):
"""
predicts classes of input image
:param test_img: filepath to image to predict on
:param show: displays segmentation results
:return: segmented result
"""
img = np.array( rgb2gray( imread( test_img ).astype( 'float' ) ).reshape( 5, 216, 160 )[-2] ) / 256
plist = []
# create patches from an entire slice
img_1 = adjust_sigmoid( img ).astype( float )
edges_1 = adjust_sigmoid( img, inv=True ).astype( float )
edges_2 = img_1
edges_5_n = normalize( laplace( img_1 ) )
edges_5_n = img_as_float( img_as_ubyte( edges_5_n ) )
plist.append( extract_patches_2d( edges_1, (23, 23) ) )
plist.append( extract_patches_2d( edges_2, (23, 23) ) )
plist.append( extract_patches_2d( edges_5_n, (23, 23) ) )
patches = np.array( zip( np.array( plist[0] ), np.array( plist[1] ), np.array( plist[2] ) ) )
# predict classes of each pixel based on model
full_pred = self.model.predict_classes( patches )
fp1 = full_pred.reshape( 194, 138 )
return fp1
def crop_image(x, target_height=227, target_width=227):
print x
# skimage.img_as_float convert image np.ndarray into float type, with range (0, 1)
image = skimage.img_as_float(skimage.io.imread(x)).astype(np.float32)
if image.ndim == 2:
image = image[:,:,np.newaxis][:,:,[0,0,0]] # convert the gray image to rgb image
height, width, rgb = image.shape
if width == height:
resized_image = cv2.resize(image, (target_width,target_height))
elif height < width:
resized_image = cv2.resize(image, (int(width * float(target_height)/height), target_height))
cropping_length = int((resized_image.shape[1] - target_width) / 2)
resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]
else:
resized_image = cv2.resize(image, (target_width, int(height * float(target_width) / width)))
cropping_length = int((resized_image.shape[0] - target_height) / 2)
resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]
return cv2.resize(resized_image, (target_width, target_height))
def test():
test_filename = sys.argv[2]
test_image = scipy.misc.imread(test_filename, flatten=True)
test_image = scipy.misc.imresize(test_image, [background_height, background_width])
test_image = skimage.img_as_float(test_image).astype(np.float32)
model.load("find_kanji.tflearn")
Y = model.predict(test_image.reshape([-1, background_height, background_width]))[0]
print(Y)
masked = np.square(Y)
masked = scipy.misc.imresize(masked, [background_height, background_width])
masked = test_image * masked
scipy.misc.imsave("y.png", masked)
#Y_indices = np.argsort(Y)[::-1]
def _read_image(self, image_name):
"""
Read image from self._path_to_img and perform any necessary preparation
:param image_name: string, image name, which is added to self._path_to_img
:return: numpy 2d array
"""
filename = image_name
try:
img = io.imread(filename)
except IOError:
return None
img = img_as_float(img)
if len(img.shape) > 2:
img = img[:, :, 0]
img = resize(img, (self._image_width, self._image_height))
img = img.reshape((self._image_width, self._image_height, 1))
return img
def read_image(image_name, img_size=None):
"""
Read image from file
:param image_name: string, image full name including path
:param img_size: tuple of two ints, optional, specify if you want to resize image
:return: numpy 2d array
"""
filename = image_name
try:
img = io.imread(filename)
except IOError:
return None
img = img_as_float(img)
if len(img.shape) > 2:
img = img[:, :, 0]
if img_size is not None:
img = resize(img, (img_size[0], img_size[1]))
img = img.reshape((1, img_size[0], img_size[1]))
return img
def crop_image(x, target_height=227, target_width=227, as_float=True):
image = skimage.io.imread(x)
if as_float:
image = skimage.img_as_float(image).astype(np.float32)
if len(image.shape) == 2:
image = np.tile(image[:,:,None], 3)
elif len(image.shape) == 4:
image = image[:,:,:,0]
height, width, rgb = image.shape
if width == height:
resized_image = cv2.resize(image, (target_height,target_width))
elif height < width:
resized_image = cv2.resize(image, (int(width * float(target_height)/height), target_width))
cropping_length = int((resized_image.shape[1] - target_height) / 2)
resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]
else:
resized_image = cv2.resize(image, (target_height, int(height * float(target_width) / width)))
cropping_length = int((resized_image.shape[0] - target_width) / 2)
resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]
return cv2.resize(resized_image, (target_height, target_width))
def load_cifar10_batch(fpath, one_hot=True, as_float=True):
with open(fpath, 'rb') as f:
# https://stackoverflow.com/questions/11305790
data = cPickle.load(f, encoding='latin1')
X = np.copy(data['data']).reshape(-1, 32*32, 3, order='F')
X = X.reshape(-1, 32, 32, 3)
Y = np.array(data['labels'])
# Convert labels to one hot
if one_hot:
Y = to_one_hot(Y)
# CONVERT TO FLOAT [0,1] TYPE HERE to be consistent with skimage TFs!!!
# See: http://scikit-image.org/docs/dev/user_guide/data_types.html
if as_float:
X = img_as_float(X)
return X, Y
def findMaximaOnFG(self, param):
self.defineFG(param)
#self.smooth_corr()
self.coorExtract = [0, 0]
xmin, ymin = self.coorExtract
img=self.candi
img [self.FG ==0] =0
im = img_as_float(img)
image_max = ndimage.maximum_filter(im, size=10, mode='constant')
coordinates = peak_local_max(im, min_distance=10)
tep=np.zeros(self.candi.shape)
for i,ide in enumerate(coordinates):
tep[ide[0],ide[1]] = self.candi[ide[0],ide[1]]
lbl = ndimage.label(tep)[0]
centerc = np.round(ndimage.measurements.center_of_mass(tep, lbl, range(1,np.max(lbl)+1)))
if centerc.size > 0:
self.centersX = centerc[:,0].astype(int)
self.centersY = centerc[:,1].astype(int)
self.nComponents = len(self.centersX)
def test_rgb2hsv_conversion(self):
rgb = img_as_float(self.img_rgb)[::16, ::16]
hsv = rgb2hsv(rgb).reshape(-1, 3)
# ground truth from colorsys
gt = np.array([colorsys.rgb_to_hsv(pt[0], pt[1], pt[2])
for pt in rgb.reshape(-1, 3)]
)
assert_almost_equal(hsv, gt)
def test_xyz_rgb_roundtrip(self):
img_rgb = img_as_float(self.img_rgb)
assert_array_almost_equal(xyz2rgb(rgb2xyz(img_rgb)), img_rgb)
# RGB<->HED roundtrip with ubyte image
def test_hed_rgb_float_roundtrip(self):
img_rgb = img_as_float(self.img_rgb)
assert_array_almost_equal(hed2rgb(rgb2hed(img_rgb)), img_rgb)
# RGB<->HDX roundtrip with ubyte image
def test_hdx_rgb_roundtrip(self):
from skimage.color.colorconv import hdx_from_rgb, rgb_from_hdx
img_rgb = img_as_float(self.img_rgb)
conv = combine_stains(separate_stains(img_rgb, hdx_from_rgb),
rgb_from_hdx)
assert_array_almost_equal(conv, img_rgb)
# RGB to RGB CIE
def test_lab_rgb_roundtrip(self):
img_rgb = img_as_float(self.img_rgb)
assert_array_almost_equal(lab2rgb(rgb2lab(img_rgb)), img_rgb)
# test matrices for xyz2luv and luv2xyz generated using
# http://www.easyrgb.com/index.php?X=CALC
# Note: easyrgb website displays xyz*100
def test_lab_lch_roundtrip(self):
rgb = img_as_float(self.img_rgb)
lab = rgb2lab(rgb)
lab2 = lch2lab(lab2lch(lab))
assert_array_almost_equal(lab2, lab)
def test_rgb_lch_roundtrip(self):
rgb = img_as_float(self.img_rgb)
lab = rgb2lab(rgb)
lch = lab2lch(lab)
lab2 = lch2lab(lch)
rgb2 = lab2rgb(lab2)
assert_array_almost_equal(rgb, rgb2)
def _get_lab0(self):
rgb = img_as_float(self.img_rgb[:1, :1, :])
return rgb2lab(rgb)[0, 0, :]
def test_each_channel():
filtered = edges_each(COLOR_IMAGE)
for i, channel in enumerate(np.rollaxis(filtered, axis=-1)):
expected = img_as_float(filters.sobel(COLOR_IMAGE[:, :, i]))
assert_allclose(channel, expected)
def to_float(x):
return img_as_float(x)
def _normalise_image(image, *, image_cmap=None):
image = img_as_float(image)
if image.ndim == 2:
if image_cmap is None:
image = gray2rgb(image)
else:
image = plt.get_cmap(image_cmap)(image)[..., :3]
return image
def create_image_lmdb(target, samples, bgr=BGR, normalize=False):
"""Create an image LMDB
Args:
target (str): path of the LMDB to be created
samples (array list): list of images to be included in the LMDB
bgr (bool): True if we want to reverse the channel order (RGB->BGR)
normalize (bool): True if we want to normalize data in [0,1]
"""
# Open the LMDB
if os.path.isdir(target):
raise Exception("LMDB already exists in {}, aborted.".format(target))
db = lmdb.open(target, map_size=int(1e12))
with db.begin(write=True) as txn:
for idx, sample in tqdm(enumerate(samples), total=len(samples)):
sample = io.imread(sample)
# load image:
if normalize:
# - in [0,1.]float range
sample = img_as_float(sample)
if bgr:
# - in BGR (reverse from RGB)
sample = sample[:,:,::-1]
# - in Channel x Height x Width order (switch from H x W x C)
sample = sample.transpose((2,0,1))
datum = caffe.io.array_to_datum(sample)
# Write the data into the db
txn.put('{:0>10d}'.format(idx), datum.SerializeToString())
db.close()
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 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