本文整理汇总了Python中skimage.img_as_ubyte函数的典型用法代码示例。如果您正苦于以下问题:Python img_as_ubyte函数的具体用法?Python img_as_ubyte怎么用?Python img_as_ubyte使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了img_as_ubyte函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: saver
def saver(stepName, img, dbg=None, mode=mode):
path = (processedDir / str(imgName)).with_suffix(".{}.png".format(stepName) if stepName else ".png")
if mode == 'cache' and processedDir and imgName:
mode = 'save'
if path.exists():
print("Loading cached image:", path)
img = ski.img_as_ubyte(io.imread(str(path)))
mode = 'done'
elif isinstance(img,type(None)):
print("Caching image:", path)
img = ski.img_as_ubyte(io.imread(str(imgName)))
assert not isinstance(img,type(None))
if mode == 'save' and processedDir and imgName:
try:
print("Saving:", img.shape, img.dtype, path.name, flush=True, )
pil_img = PIL.Image.fromarray(img_as_ubyte(img))
pil_img.save(str(path))
if dbg:
dbg.saved_path = path
except Exception as err:
print("Error Saving:",path, err, flush=True, )
elif mode == 'plot':
plt.imshow(img)
plt.suptitle(stepName+" "+imgName.name)
plt.show(block=True)
plt.close()
return img
示例2: 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)
示例3: _handle_input
def _handle_input(image, selem, out, mask, out_dtype=None):
if image.dtype not in (np.uint8, np.uint16):
image = img_as_ubyte(image)
selem = np.ascontiguousarray(img_as_ubyte(selem > 0))
image = np.ascontiguousarray(image)
if mask is None:
mask = np.ones(image.shape, dtype=np.uint8)
else:
mask = img_as_ubyte(mask)
mask = np.ascontiguousarray(mask)
if out is None:
if out_dtype is None:
out_dtype = image.dtype
out = np.empty_like(image, dtype=out_dtype)
if image is out:
raise NotImplementedError("Cannot perform rank operation in place.")
is_8bit = image.dtype in (np.uint8, np.int8)
if is_8bit:
max_bin = 255
else:
max_bin = max(4, image.max())
bitdepth = int(np.log2(max_bin))
if bitdepth > 10:
warnings.warn("Bitdepth of %d may result in bad rank filter "
"performance due to large number of bins." % bitdepth)
return image, selem, out, mask, max_bin
示例4: define_matrix
def define_matrix(image, number_of_iterations = 5000, termination_eps = 1e-10, warp = 'Affine'):
warp_mode_dct = {
'Translation' : cv2.MOTION_TRANSLATION,
'Affine' : cv2.MOTION_AFFINE,
'Euclidean' : cv2.MOTION_EUCLIDEAN,
'Homography' : cv2.MOTION_HOMOGRAPHY
}
img = oib.image_reorder(image)
color1 = img_as_ubyte(img[0,0,:,:,0])
color2 = img_as_ubyte(img[0,0,:,:,1])
warp_mode = warp_mode_dct.pop('%s' % warp)
if warp_mode == cv2.MOTION_HOMOGRAPHY :
warp_matrix = np.eye(3, 3, dtype=np.float32)
else :
warp_matrix = np.eye(2, 3, dtype=np.float32)
number_of_iterations = number_of_iterations
termination_eps = termination_eps
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations, termination_eps)
(cc, warp_matrix) = cv2.findTransformECC (color1,color2,warp_matrix, warp_mode, criteria)
return warp_matrix
示例5: worker
def worker(input_file_path, queue):
int_values = []
path_sections = input_file_path.split("/")
for string in path_sections:
if re.search(r'\d+', string) is not None:
int_values.append(int(re.search(r'\d+', string).group()))
file_count = int_values[-1]
image = cv2.imread(input_file_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
edges = img_as_ubyte(canny(image, sigma=canny_sigma))
img_bw = cv2.threshold(edges, 250, 255, cv2.THRESH_BINARY)[1]
point = _find_bottom_edge(img_bw)
try:
distance = len(img_bw) - point[1]
except TypeError:
try:
edges = img_as_ubyte(canny(image, sigma=canny_sigma_closeup))
img_bw = cv2.threshold(edges, 250, 255, cv2.THRESH_BINARY)[1]
distance = len(img_bw) - point[1]
except TypeError:
distance = 0
output = str(file_count) + ":" + str(distance) + "\n"
queue.put(output)
return output
示例6: _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
示例7: dilation
def dilation(image, selem=None, out=None, shift_x=False, shift_y=False):
"""Return greyscale morphological dilation of an image.
Morphological dilation sets a pixel at (i,j) to the maximum over all pixels
in the neighborhood centered at (i,j). Dilation enlarges bright regions
and shrinks dark regions.
Parameters
----------
image : ndarray
Image array.
selem : ndarray, optional
The neighborhood expressed as a 2-D array of 1's and 0's.
If None, use cross-shaped structuring element (connectivity=1).
out : ndarray, optional
The array to store the result of the morphology. If None, is
passed, a new array will be allocated.
shift_x, shift_y : bool, optional
shift structuring element about center point. This only affects
eccentric structuring elements (i.e. selem with even numbered sides).
Returns
-------
dilated : uint8 array
The result of the morphological dilation.
Notes
-----
For `uint8` (and `uint16` up to a certain bit-depth) data, the lower
algorithm complexity makes the `skimage.filter.rank.maximum` function more
efficient for larger images and structuring elements.
Examples
--------
>>> # Dilation enlarges bright regions
>>> import numpy as np
>>> from skimage.morphology import square
>>> bright_pixel = np.array([[0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 1, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0]], dtype=np.uint8)
>>> dilation(bright_pixel, square(3))
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
"""
if image is out:
raise NotImplementedError("In-place dilation not supported!")
image = img_as_ubyte(image)
selem = img_as_ubyte(selem)
return cmorph._dilate(image, selem, out=out,
shift_x=shift_x, shift_y=shift_y)
示例8: preprocess
def preprocess(filename):
image = img_as_ubyte(io.imread(filename, as_grey = True))
if image.shape[0] != 768:
print(image.shape)
print("WARN: Resizing image to old iPad Size. TODO> Move forward to retina images!")
return img_as_ubyte(transform.resize(image, (768, 1024)))
return image
示例9: test_threshold_minimum
def test_threshold_minimum():
camera = skimage.img_as_ubyte(data.camera())
threshold = threshold_minimum(camera)
assert_equal(threshold, 76)
astronaut = skimage.img_as_ubyte(data.astronaut())
threshold = threshold_minimum(astronaut)
assert_equal(threshold, 114)
示例10: dynamic_masking
def dynamic_masking(image,method='edges',filter_size=7,threshold=0.005):
""" Dynamically masks out the objects in the PIV images
Parameters
----------
image: image
a two dimensional array of uint16, uint8 or similar type
method: string
'edges' or 'intensity':
'edges' method is used for relatively dark and sharp objects, with visible edges, on
dark backgrounds, i.e. low contrast
'intensity' method is useful for smooth bright objects or dark objects or vice versa,
i.e. images with high contrast between the object and the background
filter_size: integer
a scalar that defines the size of the Gaussian filter
threshold: float
a value of the threshold to segment the background from the object
default value: None, replaced by sckimage.filter.threshold_otsu value
Returns
-------
image : array of the same datatype as the incoming image with the object masked out
as a completely black region(s) of zeros (integers or floats).
Example
--------
frame_a = openpiv.tools.imread( 'Camera1-001.tif' )
imshow(frame_a) # original
frame_a = dynamic_masking(frame_a,method='edges',filter_size=7,threshold=0.005)
imshow(frame_a) # masked
"""
imcopy = np.copy(image)
# stretch the histogram
image = exposure.rescale_intensity(img_as_float(image), in_range=(0, 1))
# blur the image, low-pass
blurback = img_as_ubyte(gaussian_filter(image,filter_size))
if method is 'edges':
# identify edges
edges = sobel(blurback)
blur_edges = gaussian_filter(edges,21)
# create the boolean mask
bw = (blur_edges > threshold)
bw = img_as_ubyte(binary_fill_holes(bw))
imcopy -= blurback
imcopy[bw] = 0.0
elif method is 'intensity':
background = gaussian_filter(median_filter(image,filter_size),filter_size)
imcopy[background > threshold_otsu(background)] = 0
return imcopy #image
示例11: test_divide_and_reassemble
def test_divide_and_reassemble(self):
pic = img_as_ubyte(io.imread("./kitteh.jpg"))
pic = resize(pic, (500,500), mode='nearest')
pic = img_as_ubyte(pic)
print "size "+str(pic.shape)
for shape in [(10,10),(10,20),(30,30),(33,48)]:
print shape
parts = divide_into_parts(pic,*shape)
pic2 = assemble_from_parts(parts, False, False)
self.assertTrue((pic==pic2).all())
示例12: open_image
def open_image(address):
image = imread(address)
gray_image = rgb2gray(image)
r = image[:,:,0]
g = image[:,:,1]
b = image[:,:,2]
#
# m,n,_ = image.shape
#
# gray_image = img_as_ubyte(gray_image)
return img_as_ubyte(gray_image), img_as_ubyte(r), img_as_ubyte(g), img_as_ubyte(b)
示例13: test_threshold_minimum
def test_threshold_minimum():
camera = skimage.img_as_ubyte(data.camera())
threshold = threshold_minimum(camera)
assert threshold == 76
threshold = threshold_minimum(camera, bias='max')
assert threshold == 77
astronaut = skimage.img_as_ubyte(data.astronaut())
threshold = threshold_minimum(astronaut)
assert threshold == 117
示例14: load_disp_image
def load_disp_image(self, img_name,j,display_only=False):
print ("Setting image: %s" % str(img_name))
try:
temp_img = img_as_ubyte(imread(img_name))
except:
print("Error reading file, setting zero image")
h_img=self.exp1.active_params.m_params.imx
v_img=self.exp1.active_params.m_params.imy
temp_img = img_as_ubyte(np.zeros((h_img,v_img)))
if not display_only:
ptv.py_set_img(temp_img,j)
if len(temp_img)>0:
self.camera_list[j].update_image(temp_img)
示例15: dilation
def dilation(image, selem, out=None, shift_x=False, shift_y=False):
"""Return greyscale morphological dilation of an image.
Morphological dilation sets a pixel at (i,j) to the maximum over all pixels
in the neighborhood centered at (i,j). Dilation enlarges bright regions
and shrinks dark regions.
Parameters
----------
image : ndarray
Image array.
selem : ndarray
The neighborhood expressed as a 2-D array of 1's and 0's.
out : ndarray
The array to store the result of the morphology. If None, is
passed, a new array will be allocated.
shift_x, shift_y : bool
shift structuring element about center point. This only affects
eccentric structuring elements (i.e. selem with even numbered sides).
Returns
-------
dilated : uint8 array
The result of the morphological dilation.
Examples
--------
>>> # Dilation enlarges bright regions
>>> import numpy as np
>>> from skimage.morphology import square
>>> bright_pixel = np.array([[0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 1, 0, 0],
... [0, 0, 0, 0, 0],
... [0, 0, 0, 0, 0]], dtype=np.uint8)
>>> dilation(bright_pixel, square(3))
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
"""
if image is out:
raise NotImplementedError("In-place dilation not supported!")
image = img_as_ubyte(image)
selem = img_as_ubyte(selem)
return cmorph._dilate(image, selem, out=out,
shift_x=shift_x, shift_y=shift_y)