本文整理汇总了Python中skimage.filter.threshold_otsu函数的典型用法代码示例。如果您正苦于以下问题:Python threshold_otsu函数的具体用法?Python threshold_otsu怎么用?Python threshold_otsu使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了threshold_otsu函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: adaptive_none
def adaptive_none(self, grid_number):
# First divide the image into number of grid.
# Total, grid_number^2 number of grids.
# 7, 5 are not working
x, y = 0, 0
img = deepcopy(self.img)
while(True):
# Find left upper corner only.
if x + grid_number >= self.col and y + grid_number >= self.row:
# at last grid.
subimg = self.img[y: , x: ]
opt = threshold_otsu(subimg)
img[y:, x:] = self.img[y:, x:] > opt
break
elif x + grid_number >= self.col and y + grid_number < self.row:
# at the right edge.
subimg = self.img[y : y + grid_number, x :]
opt = threshold_otsu(subimg)
img[y : y + grid_number, x :] = self.img[y : y + grid_number, x :] > opt
y = y+grid_number
x = 0
elif x + grid_number < self.col and y + grid_number >= self.row:
subimg = self.img[y : , x : x + grid_number]
opt = threshold_otsu(subimg)
img[y : , x : x + grid_number] = self.img[y : , x : x + grid_number] > opt
# print self.img[y : , x : x + width]
x = x + grid_number
else:
subimg = self.img[y : y + grid_number, x : x + grid_number]
opt = threshold_otsu(subimg)
img[y : y + grid_number, x : x + grid_number] = self.img[y : y + grid_number, x : x + grid_number] > opt
# print self.img[y : y + height, x : x + width]
x = x+grid_number
return img
示例2: main
def main():
parser = OptionParser()
(options, args) = parser.parse_args()
# reading input files
path = args[0]
# ref is the image that is used as a reference to subtract the background.
roi = [125,125,1050,1250]
roi_minx = roi[0]
roi_miny = roi[1]
roi_maxx = roi[2]
roi_maxy = roi[3]
template = io.imread(args[1])
template = template[:,:,0]
#ref = ref[roi_minx:roi_maxx, roi_miny:roi_maxy]
# otsu threshold the ref
thresh = filter.threshold_otsu(template)
template = template < thresh
#plt.imshow(ref)
#plt.show()
ref = io.imread(args[2])
ref = ref[:,:,0]
ref = ref[roi_minx:roi_maxx, roi_miny:roi_maxy]
thresh = filter.threshold_otsu(ref)
ref= ref < thresh
#plt.imshow(ref)
#plt.show()
output = []
for subdir, dirs, files in os.walk(path):
for file in files:
fn = os.path.join(subdir, file)
img = io.imread(fn)
img = img[:,:,0]
img = img[roi_minx:roi_maxx, roi_miny:roi_maxy]
# do otsu thresholding
thresh = filter.threshold_otsu(img)
img = img < thresh
#img = abs(img-ref)
#plt.imshow(img)
#plt.show()
centers = find_centers(img,template)
# get the image number from the file
n = int(re.search(r'\d+', file).group())
output.append((n, centers))
output = sorted(output, key=lambda x:x[0])
# now post process the output
post_process(output,roi)
示例3: generate_template
def generate_template(digit_dir_path):
template = zeros((42, 42))
for filename in iglob(digit_dir_path + '/*.bmp'):
img = imread(filename)
img = resize(img, [44, 44])
img = img[1:43,1:43]
img = (img > (threshold_otsu(img, nbins=256)))
template += img
template = (template < (threshold_otsu(template, nbins=256)-5))
return template
示例4: robertCross
def robertCross(A):
robert_minus=np.array([[1,0],[0,-1]])
robert_plus=np.array([[0,1],[-1,0]])
result1=convolution(A,robert_minus);
result1=np.abs(result1)
thresh1=np.floor(threshold_otsu(result1))
result1=np.logical_or(result1<0,result1>thresh1)
result2=convolution(A,robert_plus);
result2=np.abs(result2)
thresh2=np.floor(threshold_otsu(result2))
result2=np.logical_or(result2<0,result2>thresh2)
result=np.logical_or(result1,result2);
return result
示例5: scikit_otsu
def scikit_otsu(img):
rows,cols,depth=img.shape
from skimage.filter import threshold_otsu
print "threshold using scikit" , np.floor(threshold_otsu(img))
threshold=np.floor(threshold_otsu(img))
imgO=np.zeros((rows,cols),int)
for i in range(cols):
for j in range(rows):
if img[i,j,0]>=threshold:
imgO[i,j]=255
elif img[i,j,0]<threshold:
imgO[i,j]=0
return imgO
示例6: percent_vert_horiz_lines
def percent_vert_horiz_lines(FilledBlobImg, props_area):
v = filter.vsobel(FilledBlobImg)
v_floor = filter.threshold_otsu(v)
ind_v = np.where(v > v_floor)
h = filter.hsobel(FilledBlobImg)
h_floor = filter.threshold_otsu(h)
ind_h = np.where(h > h_floor)
vert_and_horiz = np.zeros(v.shape).astype("bool")
vert_and_horiz[ind_v] = True
vert_and_horiz[ind_h] = True
ind = np.where(vert_and_horiz)[0]
return float(ind.size) / props_area
示例7: ifcb_segment
def ifcb_segment(img):
Y = img_as_float(img)
# step 1. local variance
Yv = rescale_intensity(generic_filter(Y, np.var, footprint=disk(3)))
# step 2. threshold local variance, aggressively
Ye = Yv > (threshold_otsu(Yv) / 2.)
# step 3. dark areas
Yt = Y < threshold_otsu(Y)
thin_blob = Ye | Yt
# step 4. morphological reconstruction
seed = np.copy(thin_blob)
seed[1:-1,1:-1] = 1
four=np.disk(1).astype(np.bool)
return reconstruction(seed,thin_blob,method='erosion',selem=four)
示例8: plot_preprocessed_image
def plot_preprocessed_image(self):
"""
plots pre-processed image. The plotted image is the same as obtained at the end
of the get_text_candidates method.
"""
image = restoration.denoise_tv_chambolle(self.image, weight=0.1)
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(2))
cleared = bw.copy()
label_image = measure.label(cleared)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
image_label_overlay = label2rgb(label_image, image=image)
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(12, 12))
ax.imshow(image_label_overlay)
for region in regionprops(label_image):
if region.area < 10:
continue
minr, minc, maxr, maxc = region.bbox
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='red', linewidth=2)
ax.add_patch(rect)
plt.show()
示例9: one_file_features
def one_file_features(self, im, demo=False):
"""
Zde je kontruován vektor příznaků pro klasfikátor
"""
fd = np.array([])
import skimage.transform
import skimage
# Zmena velikosti obrazku
image = skimage.transform.resize(im, [50, 50])
#%% Vyriznuti objektu kolem stredu obrazu
image = image[int(image.shape[0]/2)-20:int(image.shape[0]/2)+20, int(image.shape[1]/2)-20:int(image.shape[1]/2)+20]
fd = np.append(fd, image.reshape(-1))
# Vyuziti Otsuova filtru
from skimage import filter
threshold = filter.threshold_otsu(image)
image =image < threshold
fd = np.append(fd, image.reshape(-1))
#%% Změna velikosti
#fd.append(hsvft[:])
# if self.colorFeatures:
# fd = np.append(fd, self.colorFeatures)
# pass
return fd
示例10: __transform
def __transform(self):
self.__img_gray = io.imread(self.__img_path, True)
self.__otsu = filter.threshold_otsu(self.__img_gray) #Aplicar otsu para binarizar a imagem
self.__img_gray = self.__img_gray < self.__otsu
# Find contours at a constant value of 0.5
self.__contours = measure.find_contours(self.__img_gray, 0.5)
self.__arclen = 0.0
for n, contour in enumerate(self.__contours):
arclenTemp=0.0
for indice, valor in enumerate(contour):
if indice > 0:
d1 = math.fabs(round(valor[0]) - round(contour[indice-1,0]))
d2 = math.fabs(round(valor[1]) - round(contour[indice-1,1]))
if d1+d2>1.0:
arclenTemp+=math.sqrt(2)
elif d1+d2 == 1:
arclenTemp+=1
if arclenTemp > self.__arclen:
self.__arclen = arclenTemp
self.__bestn = n
#self.__bestn = 0
print self.__contours[0]
示例11: scikit_example_plot_label
def scikit_example_plot_label():
image = data.coins()[50:-50, 50:-50]
# apply threshold
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(3))
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(label_image, cmap='jet')
for region in regionprops(label_image, ['Area', 'BoundingBox']):
# skip small images
if region['Area'] < 100:
continue
# draw rectangle around segmented coins
minr, minc, maxr, maxc = region['BoundingBox']
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='red', linewidth=2)
ax.add_patch(rect)
plt.show()
示例12: label_stack
def label_stack(z_stack, parameters):
'''
Apply an automated threshold and a watershed algorithm to
label cells in each planes of the stack
Parameters:
-----------
z_stack: 3d array of shape (nz, nx, ny)
Returns:
--------
labeled_stack: 3d array of the same shape as z_stack,
with each detected region labeled
'''
segment_method = parameters['segment_method']
correction = parameters['correction']
labeled_stack = np.zeros(z_stack.shape, dtype=np.uint8)
max_int_proj = z_stack.max(axis=0)
thresh = None
if segment_method == 'otsu':
thresh = threshold_otsu(max_int_proj) * correction
elif segment_method == 'naive':
thresh = max_int_proj.max() * correction
else:
err_string = ('Segmentation method {}'
'is not implemented'.format(segment_method))
raise NotImplementedError(err_string)
while thresh > z_stack.max():
log.warning('''Reducing threshold''')
thresh *= 0.9
for n, frame in enumerate(z_stack):
labeled_stack[n] = label_from_thresh(frame, thresh, parameters)
return labeled_stack
示例13: threshold_image
def threshold_image(image, threshold=0):
"""
This function takes out any values in an image's RGB matrix that are
below the threshold value.
Inputs:
- image: a matrix describing an image with only one channel represented.
- threshold: a value, between 0 and 1, for which if an image matrix's
value is below, will be set to 0, and if above, will be
set to 1.
If the threshold is set to 0, then an Otsu thresholding will
be returned.
Outputs:
- thresholded_image: a matrix representation of the thresholded image.
this is essentially a black and white image.
- thresh: the threshold value
To screen: the black-and-white image representation.
-
"""
if threshold == 0:
thresh = threshold_otsu(image)
if threshold != 0:
thresh = threshold
thresholded_image = closing(image > thresh, square(3), out=None)
imshow(thresholded_image)
return thresholded_image, thresh
示例14: variance_otsu
def variance_otsu(image, labels):
"""
Read pixel intensities from 'image' for each class given in 'labels' (a corresponding cluster
label array), and use Otsu's binarisation to threshold the image.
:param image: Pre-processed input image
:param labels: Array with same shape as input image, containing cluster labels
"""
img = image.ravel()
shadow_seg = img.copy()
hist, _ = np.histogram(labels)
n_clusters = hist.shape[0]
for i in range(0, n_clusters):
# set up mask of pixel indices matching cluster
mask = np.nonzero((labels.ravel() == i) == True)[0]
if len(mask) > 0:
if img[mask].var() > 0.005:
thresh = threshold_otsu(img[mask])
shadow_seg[mask] = shadow_seg[mask] < thresh
else:
shadow_seg[mask] = 0
shadow_seg = shadow_seg.reshape(*image.shape)
return shadow_seg
示例15: watershed_3d
def watershed_3d(sphere):
"""
Markers should be int8
Image should be uint8
"""
sphere = median_filter(sphere, 3)
thresh = threshold_otsu(sphere)
sphere = (sphere >= thresh) * 1
sphere = sobel(sphere)
size = (sphere.shape[0], sphere.shape[1], sphere.shape[2])
marker = np.zeros(size, dtype=np.int16)
pl.imshow(sphere[:,:,50])
pl.show()
# mark everything outside as background
marker[5, :, :] = -1
marker[size[0] - 5, :, :] = -1
marker[:, :, 5] = -1
marker[:, :, size[2] - 5] = -1
marker[:, 5, :] = -1
marker[:, size[1] - 5, :] = -1
marker[:,0,0] = -1
# mark everything inside as a sphere
marker[size[0] / 2., size[1] / 2., size[2] / 2.] = 5
result = measurements.watershed_ift(sphere.astype(dtype=np.uint16), marker)
pl.imshow(result[:,:,50])
pl.show()
return result