本文整理汇总了Python中skimage.filters.threshold_otsu方法的典型用法代码示例。如果您正苦于以下问题:Python filters.threshold_otsu方法的具体用法?Python filters.threshold_otsu怎么用?Python filters.threshold_otsu使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类skimage.filters
的用法示例。
在下文中一共展示了filters.threshold_otsu方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: project_object_edge
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def project_object_edge(img, dimension):
""" scale the image, binarise with Othu and project to one dimension
:param ndarray img:
:param int dimension: select dimension for projection
:return list(float):
>>> img = np.zeros((20, 10, 3))
>>> img[2:6, 1:7, :] = 1
>>> img[10:17, 4:6, :] = 1
>>> project_object_edge(img, 0).tolist() # doctest: +NORMALIZE_WHITESPACE
[0.0, 0.0, 0.7, 0.7, 0.7, 0.7, 0.0, 0.0, 0.0, 0.0,
0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.0, 0.0, 0.0]
"""
assert dimension in (0, 1), 'not supported dimension %i' % dimension
assert img.ndim == 3, 'unsupported image shape %r' % img.shape
img_gray = np.mean(img, axis=-1)
img_gray = GaussianBlur(img_gray, (5, 5), 0)
p_low, p_high = np.percentile(img_gray, (1, 95))
img_gray = rescale_intensity(img_gray, in_range=(p_low, p_high))
img_bin = img_gray > threshold_otsu(img_gray)
img_edge = np.mean(img_bin, axis=1 - dimension)
return img_edge
示例2: run
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def run(args):
logging.basicConfig(level=logging.INFO)
slide = openslide.OpenSlide(args.wsi_path)
# note the shape of img_RGB is the transpose of slide.level_dimensions
img_RGB = np.transpose(np.array(slide.read_region((0, 0),
args.level,
slide.level_dimensions[args.level]).convert('RGB')),
axes=[1, 0, 2])
img_HSV = rgb2hsv(img_RGB)
background_R = img_RGB[:, :, 0] > threshold_otsu(img_RGB[:, :, 0])
background_G = img_RGB[:, :, 1] > threshold_otsu(img_RGB[:, :, 1])
background_B = img_RGB[:, :, 2] > threshold_otsu(img_RGB[:, :, 2])
tissue_RGB = np.logical_not(background_R & background_G & background_B)
tissue_S = img_HSV[:, :, 1] > threshold_otsu(img_HSV[:, :, 1])
min_R = img_RGB[:, :, 0] > args.RGB_min
min_G = img_RGB[:, :, 1] > args.RGB_min
min_B = img_RGB[:, :, 2] > args.RGB_min
tissue_mask = tissue_S & tissue_RGB & min_R & min_G & min_B
np.save(args.npy_path, tissue_mask)
示例3: threshold_segmentation
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def threshold_segmentation(img):
# calculate the overview level size and retrieve the image
img_hsv = img.convert('HSV')
img_hsv_np = np.array(img_hsv)
# dilate image and then threshold the image
schannel = img_hsv_np[:, :, 1]
mask = np.zeros(schannel.shape)
schannel = dilation(schannel, star(3))
schannel = ndimage.gaussian_filter(schannel, sigma=(5, 5), order=0)
threshold_global = threshold_otsu(schannel)
mask[schannel > threshold_global] = FOREGROUND
mask[schannel <= threshold_global] = BACKGROUND
return mask
示例4: __call__
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def __call__(self, image, test):
image_data = numpy.asarray(image, dtype=numpy.float32)[:, :, :3]
rgb_image_data = image_data.transpose(2, 0, 1)
lab_image_data = rgb2lab(image_data / 255).transpose(2, 0, 1).astype(numpy.float32)
luminous_image_data = lab_image_data[0].astype(numpy.uint8)
try:
th = threshold_otsu(luminous_image_data)
except:
import traceback
print(traceback.format_exc())
th = 0
linedrawing = (luminous_image_data > th).astype(numpy.float32)
linedrawing = numpy.expand_dims(linedrawing, axis=0)
return lab_image_data, linedrawing, rgb_image_data
示例5: get_dark_mask
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def get_dark_mask(full_data):
#get darker objects that are unlikely to be worm
if full_data.shape[0] < 2:
#nothing to do here returning
return np.zeros((full_data.shape[1], full_data.shape[2]), np.uint8)
#this mask shoulnd't contain many worms
img_h = cv2.medianBlur(np.max(full_data, axis=0), 5)
#this mask is likely to contain a lot of worms
img_l = cv2.medianBlur(np.min(full_data, axis=0), 5)
#this is the difference (the tagged pixels should be mostly worms)
img_del = img_h-img_l
th_d = threshold_otsu(img_del)
#this is the maximum of the minimum pixels of the worms...
th = np.max(img_l[img_del>th_d])
#this is what a darkish mask should look like
dark_mask = cv2.dilate((img_h<th).astype(np.uint8), disk(11))
return dark_mask
示例6: MaxBodyBox
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def MaxBodyBox(input):
Otsu=filters.threshold_otsu(input[input.shape[0]//2])
Seg=np.zeros(input.shape)
Seg[input>=Otsu]=255
Seg=Seg.astype(np.int)
ConnectMap=label(Seg, connectivity= 2)
Props = regionprops(ConnectMap)
Area=np.zeros([len(Props)])
Area=[]
Bbox=[]
for j in range(len(Props)):
Area.append(Props[j]['area'])
Bbox.append(Props[j]['bbox'])
Area=np.array(Area)
Bbox=np.array(Bbox)
argsort=np.argsort(Area)
Area=Area[argsort]
Bbox=Bbox[argsort]
Area=Area[::-1]
Bbox=Bbox[::-1,:]
MaximumBbox=Bbox[0]
return Otsu,MaximumBbox
示例7: remove_background
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def remove_background(img: np.ndarray) -> np.ndarray:
""" Remove noise using OTSU's method.
Parameters
----------
img : np.ndarray
The image to be processed
Returns
-------
np.ndarray
The image with background removed
"""
img = img.astype(np.uint8)
# Binarize the image using OTSU's algorithm. This is used to find the center
# of mass of the image, and find the threshold to remove background noise
threshold = filters.threshold_otsu(img)
# Remove noise - anything higher than the threshold. Note that the image is still grayscale
img[img > threshold] = 255
return img
示例8: predict
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def predict(obj, ctx):
"""
A prediction function.
Args:
obj (bytearray): a list of object (or a single object) to predict on
ctx (dict): a model training context
Returns:
a list with predictions
"""
binary_image = Image.open(BytesIO(obj)).convert('L')
img = resize(np.array(binary_image), (28, 28), preserve_range=True)
threshold = threshold_otsu(img)
img_colors_inverted = list(map(lambda el: 0 if el > threshold else int(255 - el), img.flatten()))
img_transformed = ctx['scaler'].transform([img_colors_inverted])
df = pd.DataFrame(img_transformed) # convert to DataFrame (pandas)
return ctx['model'].predict(df).tolist()
示例9: evaluate
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def evaluate(self,img):
img = cv2.medianBlur(img,5)
if self.auto_thresh:
self.thresh = threshold_otsu(img)
if self.white_spots:
bw = (img > self.thresh).astype(np.uint8)
else:
bw = (img <= self.thresh).astype(np.uint8)
#cv2.imshow(self.name,bw*255)
#cv2.waitKey(5)
if not .1* img.size < np.count_nonzero(bw) < .8*img.size:
print("reevaluating threshold!!")
print("Ratio:",np.count_nonzero(bw)/img.size)
print("old:",self.thresh)
self.thresh = threshold_otsu(img)
print("new:",self.thresh)
m = cv2.moments(bw)
r = {}
try:
r['x'] = m['m10']/m['m00']
r['y'] = m['m01']/m['m00']
except ZeroDivisionError:
return -1
x,y,w,h = cv2.boundingRect(bw)
#if (h,w) == img.shape:
# return -1
r['bbox'] = y,x,y+h,x+w
return r
示例10: fallback
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def fallback(self,img):
"""Called when the spots are lost"""
if self.safe_mode or self.fallback_mode:
if self.fallback_mode:
self.pipe.send("Fallback failed")
else:
self.pipe.send("[safe mode] Could not compute barycenter")
self.fallback_mode = False
return -1
self.fallback_mode = True
print("Loosing spot! Trying to reevaluate threshold...")
self.thresh = threshold_otsu(img)
return self.evaluate(img)
示例11: __call__
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def __call__(self, img_small):
m = morphology.square(self.square_size)
img_th = morphology.black_tophat(img_small, m)
img_sob = abs(filters.sobel_v(img_th))
img_closed = morphology.closing(img_sob, m)
threshold = filters.threshold_otsu(img_closed)
return img_closed > threshold
示例12: remove_noise
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def remove_noise(img):
th = filters.threshold_otsu(img)
bin_img = img > th
regions, num = ndimage.label(bin_img)
areas = []
for i in range(num):
areas.append(np.sum(regions == i+1))
img[regions != np.argmax(areas)+1] = 0
return img
示例13: compCentroid_detect1
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def compCentroid_detect1(fcn, savefolder):
data_dict = sio.loadmat(fcn)
f = matlab_style_gauss2D((10,10),0.25)
A = cv2.filter2D(data_dict['A'], -1, f)
level = threshold_otsu(A) #otsu threshold of image
bw = A > level #binary image
L,num = label(bw,8,return_num=True) #label the segmented blobs
#import pdb;pdb.set_trace()
plot_x = np.zeros((num, 1)) # location of centroid
plot_y = np.zeros((num, 1))
sum_x = np.zeros((num, 1))
sum_y = np.zeros((num, 1))
area = np.zeros((num, 1))
score = np.zeros((num, 1))
height,width = bw.shape[0], bw.shape[1]
for i in range(height):
for j in range(width):
if L[i,j] != 0:
N = L[i,j]
sum_x[N-1] = sum_x[N-1]+i*A[i,j]
sum_y[N-1] = sum_y[N-1]+j*A[i,j]
area[N-1] = area[N-1] + 1
score[N-1] = score[N-1] + A[i,j]
plot_x = np.around(sum_x*1.0/score)
plot_y = np.around(sum_y*1.0/score)
score = score*1.0/area
centroid = np.zeros((num,2))
for row in range(num):
centroid[row,0] = plot_x[row,0]
centroid[row,1] = plot_y[row,0]
#centroid = np.mat(centroid)
savefile = savefolder + fcn[-9:]
sio.savemat(savefile,{'centroid':centroid, 'area':area, 'score':score})
示例14: otsu
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def otsu(data, nbins):
from skimage.filters import threshold_otsu
thresh = threshold_otsu(data, nbins)
return data > thresh
示例15: clean_mask
# 需要导入模块: from skimage import filters [as 别名]
# 或者: from skimage.filters import threshold_otsu [as 别名]
def clean_mask(m, c):
# threshold
m_thresh = threshold_otsu(m)
c_thresh = threshold_otsu(c)
m_b = m > m_thresh
c_b = c > c_thresh
# combine contours and masks and fill the cells
m_ = np.where(m_b | c_b, 1, 0)
m_ = ndi.binary_fill_holes(m_)
# close what wasn't closed before
area, radius = mean_blob_size(m_b)
struct_size = int(1.25 * radius)
struct_el = morph.disk(struct_size)
m_padded = pad_mask(m_, pad=struct_size)
m_padded = morph.binary_closing(m_padded, selem=struct_el)
m_ = crop_mask(m_padded, crop=struct_size)
# open to cut the real cells from the artifacts
area, radius = mean_blob_size(m_b)
struct_size = int(0.75 * radius)
struct_el = morph.disk(struct_size)
m_ = np.where(c_b & (~m_b), 0, m_)
m_padded = pad_mask(m_, pad=struct_size)
m_padded = morph.binary_opening(m_padded, selem=struct_el)
m_ = crop_mask(m_padded, crop=struct_size)
# join the connected cells with what we had at the beginning
m_ = np.where(m_b | m_, 1, 0)
m_ = ndi.binary_fill_holes(m_)
# drop all the cells that weren't present at least in 25% of area in the initial mask
m_ = drop_artifacts(m_, m_b, min_coverage=0.25)
return m_