Python skimage.exposure 模块,adjust_gamma() 实例源码
我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用skimage.exposure.adjust_gamma()。
def brightness(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of a single image, randomly or non-randomly.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
gamma : float, small than 1 means brighter.
Non negative real number. Default value is 1.
- If is_random is True, gamma in a range of (1-gamma, 1+gamma).
gain : float
The constant multiplier. Default value is 1.
is_random : boolean, default False
- If True, randomly change brightness.
References
-----------
- `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`_
- `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`_
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
x = exposure.adjust_gamma(x, gamma, gain)
return x
def brightness_multi(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of multiply images, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy array
List of images with dimension of [n_images, row, col, channel] (default).
others : see ``brightness``.
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
results = []
for data in x:
results.append( exposure.adjust_gamma(data, gamma, gain) )
return np.asarray(results)
# contrast
def brightness(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of a single image, randomly or non-randomly.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
gamma : float, small than 1 means brighter.
Non negative real number. Default value is 1, smaller means brighter.
- If is_random is True, gamma in a range of (1-gamma, 1+gamma).
gain : float
The constant multiplier. Default value is 1.
is_random : boolean, default False
- If True, randomly change brightness.
References
-----------
- `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`_
- `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`_
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
x = exposure.adjust_gamma(x, gamma, gain)
return x
def brightness_multi(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of multiply images, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy array
List of images with dimension of [n_images, row, col, channel] (default).
others : see ``brightness``.
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
results = []
for data in x:
results.append( exposure.adjust_gamma(data, gamma, gain) )
return np.asarray(results)
# illumination
def brightness(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of a single image, randomly or non-randomly.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
gamma : float, small than 1 means brighter.
Non negative real number. Default value is 1.
- If is_random is True, gamma in a range of (1-gamma, 1+gamma).
gain : float
The constant multiplier. Default value is 1.
is_random : boolean, default False
- If True, randomly change brightness.
References
-----------
- `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`_
- `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`_
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
x = exposure.adjust_gamma(x, gamma, gain)
return x
def brightness_multi(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of multiply images, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy array
List of images with dimension of [n_images, row, col, channel] (default).
others : see ``brightness``.
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
results = []
for data in x:
results.append( exposure.adjust_gamma(data, gamma, gain) )
return np.asarray(results)
# contrast
def brightness(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of a single image, randomly or non-randomly.
Parameters
-----------
x : numpy array
An image with dimension of [row, col, channel] (default).
gamma : float, small than 1 means brighter.
Non negative real number. Default value is 1.
- If is_random is True, gamma in a range of (1-gamma, 1+gamma).
gain : float
The constant multiplier. Default value is 1.
is_random : boolean, default False
- If True, randomly change brightness.
References
-----------
- `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`_
- `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`_
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
x = exposure.adjust_gamma(x, gamma, gain)
return x
def brightness_multi(x, gamma=1, gain=1, is_random=False):
"""Change the brightness of multiply images, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Parameters
-----------
x : list of numpy array
List of images with dimension of [n_images, row, col, channel] (default).
others : see ``brightness``.
"""
if is_random:
gamma = np.random.uniform(1-gamma, 1+gamma)
results = []
for data in x:
results.append( exposure.adjust_gamma(data, gamma, gain) )
return np.asarray(results)
# contrast
def telemetry(sid, data):
# The current steering angle of the car
steering_angle = data["steering_angle"]
# The current throttle of the car
throttle = data["throttle"]
# The current speed of the car
speed = data["speed"]
# The current image from the center camera of the car
imgString = data["image"]
image = Image.open(BytesIO(base64.b64decode(imgString)))
image_array = np.asarray(image)
image_array = imresize(image_array, (32,64,3)).astype(np.float32)
image_array = adjust_gamma(image_array)
transformed_image_array = image_array[None, 12:, :, :].astype(np.float32)
# This model currently assumes that the features of the model are just the images. Feel free to change this.
steering_angle = float(model.predict(transformed_image_array, batch_size=1))
# The driving model currently just outputs a constant throttle. Feel free to edit this.
throttle = 0.4
print(steering_angle, throttle)
send_control(steering_angle, throttle)
def random_gamma(gamma=lambda: np.random.rand() * 0.4 + 0.8):
def call(x):
return exposure.adjust_gamma(x, gamma())
return call
def image_function(self, image):
gamma_adjusted = adjust_gamma(image,
gamma=self.get_random_variable('gamma'),
gain=self.gain)
return gamma_adjusted
def normalize_histo(image, gamma=1.0):
"""
Perform histogram normalization on image.
:param numpy array image: Numpy array with range [0,255] and dtype 'uint8'.
:param float gamma: Factor for gamma adjustment.
:return: Normalized image
:rtype: numpy array with range [0,255] and dtype 'uint8'
"""
image = ske.equalize_adapthist(image)
image = ske.adjust_gamma(image, gamma=gamma)
return floatimg2uint8(image)
def _augment(xs):
"""Image adjustment doesn't change image shape, but for intensity.
Return:
images: 4-d tensor with shape [depth, height, width, channels]
"""
# `xs` has shape [depth, height, width] with value in [0, 1].
brt_gamma, brt_gain = np.random.uniform(low=0.9, high=1.1, size=2)
aj_bright = adjust_gamma(xs, brt_gamma, brt_gain)
contrast_gain = np.random.uniform(low=5, high=10)
aj_contrast = adjust_sigmoid(aj_bright, gain=contrast_gain)
return aj_contrast
def gamma_transform(img, gamma=0.75):
return exposure.adjust_gamma(img, gamma)
def TF_adjust_gamma(x, gamma=1.0):
assert len(x.shape) == 3
h, w, nc = x.shape
return adjust_gamma(x, gamma)
def save_segmented_image(self, filepath_image, modality='t1c', show=False):
'''
Creates an image of original brain with segmentation overlay and save it in ./predictions
INPUT (1) str 'filepath_image': filepath to test image for segmentation, including file extension
(2) str 'modality': imaging modality to use as background. defaults to t1c. options: (flair, t1, t1c, t2)
(3) bool 'show': If true, shows output image. defaults to False.
OUTPUT (1) if show is True, shows image of segmentation results
(2) if show is false, returns segmented image.
'''
modes = {'flair': 0, 't1': 1, 't1c': 2, 't2': 3}
segmentation = self.predict_image(filepath_image, show=False)
print 'segmentation = ' + str(segmentation)
img_mask = np.pad(segmentation, (16, 16), mode='edge')
ones = np.argwhere(img_mask == 1)
twos = np.argwhere(img_mask == 2)
threes = np.argwhere(img_mask == 3)
fours = np.argwhere(img_mask == 4)
test_im = io.imread(filepath_image)
test_back = test_im.reshape(5, 216, 160)[modes[modality]]
# overlay = mark_boundaries(test_back, img_mask)
gray_img = img_as_float(test_back)
# adjust gamma of image
image = adjust_gamma(color.gray2rgb(gray_img), 0.65)
sliced_image = image.copy()
red_multiplier = [1, 0.2, 0.2]
yellow_multiplier = [1, 1, 0.25]
green_multiplier = [0.35, 0.75, 0.25]
blue_multiplier = [0, 0.25, 0.9]
print str(len(ones))
print str(len(twos))
print str(len(threes))
print str(len(fours))
# change colors of segmented classes
for i in xrange(len(ones)):
sliced_image[ones[i][0]][ones[i][1]] = red_multiplier
for i in xrange(len(twos)):
sliced_image[twos[i][0]][twos[i][1]] = green_multiplier
for i in xrange(len(threes)):
sliced_image[threes[i][0]][threes[i][1]] = blue_multiplier
for i in xrange(len(fours)):
sliced_image[fours[i][0]][fours[i][1]] = yellow_multiplier
#if show=True show the prediction
if show:
print 'Showing...'
io.imshow(sliced_image)
plt.show()
#save the prediction
print 'Saving...'
try:
mkdir_p('./predictions/')
io.imsave('./predictions/' + os.path.basename(filepath_image) + '.png', sliced_image)
print 'prediction saved.'
except:
io.imsave('./predictions/' + os.path.basename(filepath_image) + '.png', sliced_image)
print 'prediction saved.'
def save_segmented_image(self, index, test_img, save=False):
"""
Creates an image of original brain with segmentation overlay
:param index: index of image to save
:param test_img: filepath to test image for segmentation, including file extension
:param save: If true, shows output image. (defaults to False)
:return: if show is True, shows image of segmentation results
if show is false, returns segmented image.
"""
segmentation = self.predict_image(test_img)
img_mask = np.pad(segmentation, (16, 16), mode='edge')
ones = np.argwhere(img_mask == 1)
twos = np.argwhere(img_mask == 2)
threes = np.argwhere(img_mask == 3)
fours = np.argwhere(img_mask == 4)
test_im = mpimg.imread(test_img).astype('float')
test_back = rgb2gray(test_im).reshape(5, 216, 160)[-2]
# overlay = mark_boundaries(test_back, img_mask)
gray_img = img_as_float(test_back)
# adjust gamma of image
image = adjust_gamma(color.gray2rgb(gray_img), 0.65)
sliced_image = image.copy()
red_multiplier = [1, 0.2, 0.2]
yellow_multiplier = [1, 1, 0.25]
green_multiplier = [0.35, 0.75, 0.25]
blue_multiplier = [0, 0.25, 0.9]
# change colors of segmented classes
for i in xrange(len(ones)):
sliced_image[ones[i][0]][ones[i][1]] = red_multiplier
for i in xrange(len(twos)):
sliced_image[twos[i][0]][twos[i][1]] = green_multiplier
for i in xrange(len(threes)):
sliced_image[threes[i][0]][threes[i][1]] = blue_multiplier
for i in xrange(len(fours)):
sliced_image[fours[i][0]][fours[i][1]] = yellow_multiplier
if save:
try:
mkdir_p('./results/')
io.imsave('./results/result' + '_' + str(index) + '.png', sliced_image)
except:
io.imsave('./results/result' + '_' + str(index) + '.png', sliced_image)
else:
return sliced_image
def get_stomata(max_proj_image, min_obj_size=200, max_obj_size=1000):
"""Performs image segmentation from a max_proj_image.
Disposes of objects in range min_obj_size to
max_obj_size
:param max_proj_image: the maximum projection image
:type max_proj_image: numpy.ndarray, uint16
:param min_obj_size: minimum size of object to keep
:type min_obj_size: int
:param max_obj_size: maximum size of object to keep
:type max_obj_size: int
:returns: list of [ [coordinates of kept objects - list of slice objects],
binary object image - numpy.ndarray,
labelled object image - numpy.ndarray
]
"""
# pore_margin = 10
# max_obj_size = 1000
# min_obj_size = 200
# for prop, value in segment_options:
# if prop == 'pore_margin':
# pore_margin = value
# if prop == 'max_obj_size':
# max_obj_size = value
# if prop == 'min_obj_size':
# min_obj_size = value
#
# print(pore_margin)
# print(max_obj_size)
# print(min_obj_size)
#rescale_min = 50
#rescale_max= 100
#rescaled = exposure.rescale_intensity(max_proj_image, in_range=(rescale_min,rescale_max))
rescaled = max_proj_image
seed = np.copy(rescaled)
seed[1:-1, 1:-1] = rescaled.max()
#mask = rescaled
#if gamma != None:
# rescaled = exposure.adjust_gamma(max_proj_image, gamma)
#filled = reconstruction(seed, mask, method='erosion')
closed = dilation(rescaled)
seed = np.copy(closed)
seed[1:-1, 1:-1] = closed.max()
mask = closed
filled = reconstruction(seed, mask, method='erosion')
label_objects, nb_labels = ndimage.label(filled)
sizes = np.bincount(label_objects.ravel())
mask_sizes = sizes
mask_sizes = (sizes > min_obj_size) & (sizes < max_obj_size)
#mask_sizes = (sizes > 200) & (sizes < 1000)
mask_sizes[0] = 0
big_objs = mask_sizes[label_objects]
stomata, _ = ndimage.label(big_objs)
obj_slices = ndimage.find_objects(stomata)
return [obj_slices, big_objs, stomata]