本文整理汇总了Python中skimage.img_as_uint函数的典型用法代码示例。如果您正苦于以下问题:Python img_as_uint函数的具体用法?Python img_as_uint怎么用?Python img_as_uint使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了img_as_uint函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RQA_eval
def RQA_eval(x_in, TR, RPpow, img_process):
RQA_mat_L = zeros((TR, TR))
# Set L,R matrix to compute Recurrence matrix
RQA_mat_L[0:TR, :] = x_in
RQA_mat_R = RQA_mat_L.transpose()
if img_process == -1:
# Subtract two matirices
RQA_value = RQA_mat_L - RQA_mat_R
if img_process == 0:
# RQA_value = RQA_value/amax(abs(RQA_value))
# Subtract two matirices
RQA_value = abs(RQA_mat_L - RQA_mat_R)
RQA_value = RQA_value ** RPpow
if img_process == 1:
# RQA_value = RQA_value/amax(abs(RQA_value))
RQA_value = img_as_uint(RQA_value)
RQA_value = skimage.exposure.equalize_hist(RQA_value)
if img_process == 2:
# RQA_value = RQA_value/amax(abs(RQA_value))
RQA_value = img_as_uint(RQA_value)
RQA_value = skimage.exposure.equalize_adapthist(RQA_value, clip_limit=0.01)
RQA_value -= mean(RQA_value)
return RQA_value
示例2: mono_check
def mono_check(plugin, fmt='png'):
"""Check the roundtrip behavior for images that support most types.
All major input types should be handled.
"""
img = img_as_ubyte(data.moon())
r1 = roundtrip(img, plugin, fmt)
testing.assert_allclose(img, r1)
img2 = img > 128
r2 = roundtrip(img2, plugin, fmt)
testing.assert_allclose(img2.astype(np.uint8), r2)
img3 = img_as_float(img)
r3 = roundtrip(img3, plugin, fmt)
if r3.dtype.kind == 'f':
testing.assert_allclose(img3, r3)
else:
testing.assert_allclose(r3, img_as_uint(img))
img4 = img_as_int(img)
if fmt.lower() in (('tif', 'tiff')):
img4 -= 100
r4 = roundtrip(img4, plugin, fmt)
testing.assert_allclose(r4, img4)
else:
r4 = roundtrip(img4, plugin, fmt)
testing.assert_allclose(r4, img_as_uint(img4))
img5 = img_as_uint(img)
r5 = roundtrip(img5, plugin, fmt)
testing.assert_allclose(r5, img5)
示例3: equalize_adapthist
def equalize_adapthist(image, ntiles_x=8, ntiles_y=8, clip_limit=0.01,
nbins=256):
"""Contrast Limited Adaptive Histogram Equalization.
Parameters
----------
image : array-like
Input image.
ntiles_x : int, optional
Number of tile regions in the X direction. Ranges between 2 and 16.
ntiles_y : int, optional
Number of tile regions in the Y direction. Ranges between 2 and 16.
clip_limit : float: optional
Clipping limit, normalized between 0 and 1 (higher values give more
contrast).
nbins : int, optional
Number of gray bins for histogram ("dynamic range").
Returns
-------
out : ndarray
Equalized image.
Notes
-----
* The algorithm relies on an image whose rows and columns are even
multiples of the number of tiles, so the extra rows and columns are left
at their original values, thus preserving the input image shape.
* For color images, the following steps are performed:
- The image is converted to LAB color space
- The CLAHE algorithm is run on the L channel
- The image is converted back to RGB space and returned
* For RGBA images, the original alpha channel is removed.
References
----------
.. [1] http://tog.acm.org/resources/GraphicsGems/gems.html#gemsvi
.. [2] https://en.wikipedia.org/wiki/CLAHE#CLAHE
"""
args = [None, ntiles_x, ntiles_y, clip_limit * nbins, nbins]
if image.ndim > 2:
lab_img = color.rgb2lab(skimage.img_as_float(image))
l_chan = lab_img[:, :, 0]
l_chan /= np.max(np.abs(l_chan))
l_chan = skimage.img_as_uint(l_chan)
args[0] = rescale_intensity(l_chan, out_range=(0, NR_OF_GREY - 1))
new_l = _clahe(*args).astype(float)
new_l = rescale_intensity(new_l, out_range=(0, 100))
lab_img[:new_l.shape[0], :new_l.shape[1], 0] = new_l
image = color.lab2rgb(lab_img)
image = rescale_intensity(image, out_range=(0, 1))
else:
image = skimage.img_as_uint(image)
args[0] = rescale_intensity(image, out_range=(0, NR_OF_GREY - 1))
out = _clahe(*args)
image[:out.shape[0], :out.shape[1]] = out
image = rescale_intensity(image)
return image
示例4: test_tv_denoise_2d
def test_tv_denoise_2d(self):
"""
Apply the TV denoising algorithm on the lena image provided
by scipy
"""
# lena image
lena = color.rgb2gray(data.lena())[:256, :256]
# add noise to lena
lena += 0.5 * lena.std() * np.random.randn(*lena.shape)
# clip noise so that it does not exceed allowed range for float images.
lena = np.clip(lena, 0, 1)
# denoise
denoised_lena = filter.tv_denoise(lena, weight=60.0)
# which dtype?
assert denoised_lena.dtype in [np.float, np.float32, np.float64]
from scipy import ndimage
grad = ndimage.morphological_gradient(lena, size=((3, 3)))
grad_denoised = ndimage.morphological_gradient(
denoised_lena, size=((3, 3)))
# test if the total variation has decreased
assert np.sqrt(
(grad_denoised ** 2).sum()) < np.sqrt((grad ** 2).sum()) / 2
denoised_lena_int = filter.tv_denoise(img_as_uint(lena),
weight=60.0, keep_type=True)
assert denoised_lena_int.dtype is np.dtype('uint16')
示例5: saveRegion
def saveRegion(self):
imageBaseName = os.path.basename(
self.regionImage.fileName).split('.')[0]
pathToSave = os.path.join(workDir, imageBaseName)
for c, arr in self.imagesArrays.iteritems():
io.imsave(os.path.join(pathToSave,
'_'.join((
self._type,
str(self.timeStamp),
c, imageBaseName+'.tif'))),
img_as_uint(arr))
if self.contour is not None:
np.savetxt(os.path.join(pathToSave,
'_'.join((self._type,
str(self.timeStamp),
'contour.dat'))), self.contour)
np.savetxt(os.path.join(pathToSave,
'_'.join((self._type,
str(self.timeStamp),
'mask.dat'))), self.mask)
# pickle.dump(self.metaData,
# open(os.path.join(pathToSave, 'metaData.dat'), 'wb'))
writer = csv.writer(open(os.path.join(pathToSave,
'_'.join((self._type,
str(self.timeStamp),
'metaData.dat'))),
'wb'), delimiter=':')
self.sortedmetaData = collections.OrderedDict(sorted(
self.metaData.items()))
for k, v in self.sortedmetaData.iteritems():
writer.writerow([k, v])
示例6: _write_movie_frame
def _write_movie_frame(frame, base_path, image_filename):
"""
Takes a movie frame, adds the frame number to the bottom right of the image, and saves it to disk.
"""
# We have to set up a Matplotlib plot so we can add text.
# scikit-image unfortunately has no text annotation methods.
# fig, ax = plt.subplots()
# ax.imshow(frame, cmap=cm.gray)
#
# # Remove whitespace and ticks from the image, since we're making a movie, not a plot.
# # Matplotlib is expecting us to make a plot though, so removing all evidence of this is tricky.
# plt.gca().set_axis_off()
# plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
# plt.margins(0, 0)
# plt.gca().xaxis.set_major_locator(plt.NullLocator())
# plt.gca().yaxis.set_major_locator(plt.NullLocator())
# Add the frame number to the bottom right of the image in red text
# ax.annotate(str(frame_number + 1), xy=(1, 1), xytext=(frame.shape[1] - 9, frame.shape[0] - 5), color='r')
log.info("Creating %s" % base_path + "/" + image_filename)
# Write the frame to disk
# fig.savefig(base_path + "/" + image_filename, bbox_inches='tight', pad_inches=0)
# Closing the plot is required or memory goes nuts
# plt.close()
img = img_as_uint(frame)
skimage.io.imsave(base_path + "/" + image_filename, img, plugin='freeimage')
示例7: main
def main():
args = vars(parser.parse_args())
filename = os.path.join(os.getcwd(), args["image"][0])
image = skimage.img_as_uint(color.rgb2gray(io.imread(filename)))
subsample = 1
if (not args["subsample"] == 1):
subsample = args["subsample"][0]
image = transform.downscale_local_mean(image, (subsample, subsample))
image = transform.pyramid_expand(image, subsample, 0, 0)
image = exposure.rescale_intensity(image, out_range=(0,args["depth"][0]))
if (args["visualize"]):
io.imshow(image)
io.show()
source = generate_face(image, subsample, args["depth"][0], FLICKER_SPEED)
if source:
with open(args["output"][0], 'w') as file_:
file_.write(source)
else:
print "Attempted to generate source code, failed."
示例8: __convert_type
def __convert_type(array):
if im_type in (np.int16, np.uint16):
return img_as_uint(array)
elif im_type in (np.int8, np.uint8):
return img_as_ubyte(array)
else:
return array
示例9: run
def run(self, workspace):
x_name = self.x_name.value
y_name = self.y_name.value
images = workspace.image_set
x = images.get_image(x_name)
x_data = x.pixel_data
x_data = skimage.img_as_uint(x_data)
if x.dimensions == 3 or x.multichannel:
y_data = numpy.zeros_like(x_data)
for z, image in enumerate(x_data):
y_data[z] = skimage.filters.rank.gradient(image, self.__structuring_element())
else:
y_data = skimage.filters.rank.gradient(x_data, self.structuring_element.value)
y = cellprofiler.image.Image(
image=y_data,
dimensions=x.dimensions,
parent_image=x,
)
images.add(y_name, y)
if self.show_window:
workspace.display_data.x_data = x_data
workspace.display_data.y_data = y_data
workspace.display_data.dimensions = x.dimensions
示例10: imSave
def imSave(img, filename, range='float'):
f = open(filename,'wb')
w = png.Writer(313, 443, greyscale=True, bitdepth=8)
img_w = exposure.rescale_intensity(img,out_range=range)
img_w = img_as_uint(img_w)
w.write(f, img_w)
f.close()
示例11: test_save_buttons
def test_save_buttons():
viewer = get_image_viewer()
sv = SaveButtons()
viewer.plugins[0] += sv
import tempfile
fid, filename = tempfile.mkstemp(suffix='.png')
os.close(fid)
timer = QtCore.QTimer()
timer.singleShot(100, QtGui.QApplication.quit)
# exercise the button clicks
sv.save_stack.click()
sv.save_file.click()
# call the save functions directly
sv.save_to_stack()
with expected_warnings(['precision loss']):
sv.save_to_file(filename)
img = data.imread(filename)
with expected_warnings(['precision loss']):
assert_almost_equal(img, img_as_uint(viewer.image))
img = io.pop()
assert_almost_equal(img, viewer.image)
os.remove(filename)
示例12: test_save_im_colour_16bit
def test_save_im_colour_16bit():
im = np.random.uniform(size=(256, 256, 3))
im = img_as_uint(im)
fname = os.path.join('tests', 'test_data', 'tmp.png')
pu.image.save_im(fname, im, bitdepth=16)
im2 = io.imread(fname)
assert im.all() == im2.all()
示例13: color_check
def color_check(plugin, fmt='png'):
"""Check roundtrip behavior for color images.
All major input types should be handled as ubytes and read
back correctly.
"""
img = img_as_ubyte(data.chelsea())
r1 = roundtrip(img, plugin, fmt)
testing.assert_allclose(img, r1)
img2 = img > 128
r2 = roundtrip(img2, plugin, fmt)
testing.assert_allclose(img2.astype(np.uint8), r2)
img3 = img_as_float(img)
r3 = roundtrip(img3, plugin, fmt)
testing.assert_allclose(r3, img)
img4 = img_as_int(img)
if fmt.lower() in (('tif', 'tiff')):
img4 -= 100
r4 = roundtrip(img4, plugin, fmt)
testing.assert_allclose(r4, img4)
else:
r4 = roundtrip(img4, plugin, fmt)
testing.assert_allclose(r4, img_as_ubyte(img4))
img5 = img_as_uint(img)
r5 = roundtrip(img5, plugin, fmt)
testing.assert_allclose(r5, img)
示例14: _apply
def _apply(func8, func16, image, selem, out, mask, shift_x, shift_y):
selem = img_as_ubyte(selem > 0)
image = np.ascontiguousarray(image)
if mask is None:
mask = np.ones(image.shape, dtype=np.uint8)
else:
mask = np.ascontiguousarray(mask)
mask = img_as_ubyte(mask)
if image is out:
raise NotImplementedError("Cannot perform rank operation in place.")
is_8bit = image.dtype in (np.uint8, np.int8)
if func8 is not None and (is_8bit or func16 is None):
out = _apply8(func8, image, selem, out, mask, shift_x, shift_y)
else:
image = img_as_uint(image)
if out is None:
out = np.zeros(image.shape, dtype=np.uint16)
bitdepth = find_bitdepth(image)
if bitdepth > 11:
image = image >> 4
bitdepth = find_bitdepth(image)
func16(image, selem, shift_x=shift_x, shift_y=shift_y, mask=mask,
bitdepth=bitdepth + 1, out=out)
return out
示例15: guess_corners
def guess_corners(bw):
"""
Infer the corners of an image using a Sobel filter to find the edges and a
Harris filter to find the corners. Takes only as single color chanel.
Parameters
----------
bw : (m x n) ndarray of ints
Returns
-------
corners : pixel coordinates of plot corners, unsorted
outline : (m x n) ndarray of bools True -> plot area
"""
assert len(bw.shape) == 2
bw = img_as_uint(bw)
e_map = ndimage.sobel(bw)
markers = np.zeros(bw.shape, dtype=int)
markers[bw < 30] = 1
markers[bw > 150] = 2
seg = ndimage.watershed_ift(e_map, np.asarray(markers, dtype=int))
outline = ndimage.binary_fill_holes(1 - seg)
corners = harris(np.asarray(outline, dtype=int))
corners = approximate_polygon(corners, 1)
return corners, outline