Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
try:
from skimage import filters
except ImportError:
from skimage import filter as filters
from scipy.ndimage.filters import gaussian_filter
mat = sio.loadmat('tests/data/very-small-oof.mat', )
img = mat['img']
ostu_img = 0.
radii = np.arange(0.2, 2, 0.5)
rho = 0.5
oof_matlab = mat['oof']
ostu_matlaboof = filters.threshold_otsu(oof_matlab)
rps, _ = response(img.astype('float'), rsptype='bg', radii=radii, rho=rho)
thr = 1
from scipy import ndimage as ndi
from skimage import feature
canny = feature.canny(rps, sigma=3)
smoothed_rps = gaussian_filter(rps, 0.5)
# ostu_smooth = filters.threshold_otsu(smoothed_rps)
ostu_smooth = 1
plotidx = 1
plt.subplot(4, 4, plotidx)
plt.imshow(rps.max(axis=0))
plt.title('OOF Python MEM_SAVE YZ')
var1 = sum([(g-g1)**2 * p_g[g] for g in range(t+1, 256)])
var_between = p0 * (g0 - g_avg)**2 + p1 * (g1 - g_avg)**2
var_inner = p0 * var0**2 + p1 * var1**2
# q is the relation of variance between classes and variance within classes
q = var_between / var_inner if var_inner > 0 else 0
print(t, p0, p1, g0, g1, g_avg, var_between, var_inner, q)
if q_best is None or q_best < q:
q_best = q
threshold_best = t
img_bin_best = img <= t
# ground truth, based on scikit-image
gt_tresh = skifilters.threshold_otsu(img)
ground_truth = img <= gt_tresh
# plot
util.plot_images_grayscale(
[img, img_bin_best, ground_truth],
["Image", "Otsu", "Otsu (Ground Truth)"]
)
def getWormThreshold(pix_valid):
#calculate otsu_threshold as lower limit. Otsu understimate the threshold.
try:
otsu_thresh = threshold_otsu(pix_valid)
except:
return np.nan
#calculate the histogram
pix_hist = np.bincount(pix_valid)
#the higher limit is the most frequent value in the distribution (background)
largest_peak = np.argmax(pix_hist)
if otsu_thresh < largest_peak and otsu_thresh+2 < len(pix_hist)-1:
#smooth the histogram to find a better threshold
pix_hist = np.convolve(pix_hist, np.ones(3), 'same')
cumhist = np.cumsum(pix_hist);
xx = np.arange(otsu_thresh, cumhist.size)
try:
#the threshold is calculated as the pixel level where there would be
def get_real_images(paths):
real_images = []
for path in paths:
# Calculate a threshold to do image binarization, all colors at every pixel will be translated to number 0(white) or 1(black)
camera = io.imread(path)
val = filters.threshold_otsu(camera)
result = (camera < val)*1.0
real_images.append(result)
np_images = numpy.array(real_images)
np_images = np_images.reshape(np_images.shape[0], np_images.shape[1] * np_images.shape[2])
return np_images
# Heatmap dimensions
# *** Note y/row, x/col ordering
ny, nx = hmap.shape
# Determine blob threshold for heatmap
# Need to accommodate hotspots from longer fixations
# particularly at center.
# A single fixation blob shouldn't exceed 1% of total frame
# area so clamp heatmap to 99th percentile
pA, pB = np.percentile(hmap, (0, 99))
hmap = exposure.rescale_intensity(hmap, in_range = (pA, pB))
# Otsu threshold clamped heatmap
th = filters.threshold_otsu(hmap)
blobs = np.array(hmap > th, np.uint8)
# Morphological opening (circle 2 pixels diameter)
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
# blobs = cv2.morphologyEx(blobs, cv2.MORPH_OPEN, kernel)
# Label connected components
labels, n_labels = ndimage.label(blobs)
# Find blob centroids
# Transpose before assigning to x and y arrays
pnts = np.array(ndimage.measurements.center_of_mass(hmap, labels, range(1, n_labels+1)))
# Parse x and y coordinates
# *** Note y/row, x/col ordering
fix_x, fix_y = pnts[:,1], pnts[:,0]
def create_mask_img_3d(img, type_mask='otsu_plus', thr=0.):
assert img.ndim == 3
mask_init = np.zeros_like(img, dtype=np.bool)
if type_mask == 'threshold_plus':
mask_init[img > thr] = 1
mask_init[img <= thr] = 0
elif type_mask == 'threshold_minus':
mask_init[img < thr] = 1
mask_init[img >= thr] = 0
elif type_mask == 'otsu_plus':
if not np.any(img):
thr = 0
else:
thr = filters.threshold_otsu(img)
mask_init[img > thr] = 1
mask_init[img <= thr] = 0
elif type_mask == 'otsu_minus':
thr = filters.threshold_otsu(img)
mask_init[img < thr] = 1
mask_init[img >= thr] = 0
mask_1 = ndimg.binary_dilation(mask_init, iterations=2)
mask_bis = fill_holes(mask_1)
# mask_fin = ndimg.binary_erosion(mask_bis, iterations=2)
return mask_bis
def preprocess_input(img, show_img=False):
'''
Preprocesses an input image for futrther prediction
'''
if show_img:
print('\nOriginal image shape:', img.shape)
plt.imshow(img)
plt.title('original')
plt.show()
gray_img = rgb2gray(img)
thresh = threshold_otsu(gray_img)
# binarize to get a 'white' (255) background:
if np.mean(gray_img > thresh) > np.mean(gray_img < thresh):
gray_img[gray_img > thresh] = 255
else:
gray_img[gray_img < thresh] = 0
gray_img = 255 - gray_img
norm_img = normalize_bitmap(np.array(gray_img, dtype=np.uint8))
prepr_img = np.array(preprocess_bitmap(norm_img), dtype=np.uint8).reshape(1, *IMG_SHAPE, 1)
if show_img:
print('Preprocessed image shape:', prepr_img.shape)
plt.imshow(prepr_img.reshape(*IMG_SHAPE), cmap='gray')
plt.title('preprocessed')
plt.show()
def perform_ocr(image, scale=10, order=5, horizontal_closing=10, vertical_closing=5):
image = skimage.transform.resize(
image,
(image.shape[0] * scale, image.shape[1] * scale),
mode="edge",
order=order
)
image = image > skimage.filters.threshold_otsu(image)
black_pixel_count = image[image == 0].size
white_pixel_count = image[image == 1].size
if black_pixel_count > white_pixel_count:
image = skimage.util.invert(image)
image = skimage.morphology.closing(image, skimage.morphology.rectangle(1, horizontal_closing))
image = skimage.morphology.closing(image, skimage.morphology.rectangle(vertical_closing, 1))
image = skimage.util.img_as_ubyte(image)
if is_unix():
return tesserocr.image_to_text(
Image.fromarray(image),
psm=tesserocr.PSM.SINGLE_LINE,
x_data = skimage.exposure.rescale_intensity(x_data)
x_data = skimage.img_as_float(x_data)
y_data = numpy.zeros_like(x_data, numpy.bool)
y_data[x_data > self.lower.value] = True
y_data[x_data < self.upper.value] = False
elif self.operation.value == u"Minimum cross entropy thresholding":
y_data = skimage.filters.threshold_li(
image=x_data
)
y_data = x_data >= y_data
elif self.operation.value == u"Otsu’s method":
y_data = skimage.filters.threshold_otsu(
image=x_data,
nbins=self.bins.value
)
y_data = x_data >= y_data
elif self.operation.value == u"Yen’s method":
y_data = skimage.filters.threshold_yen(
image=x_data,
nbins=self.bins.value
)
y_data = x_data >= y_data
y = cellprofiler.image.Image(
image=y_data,
parent_image=x,
def _thresh_bw(pix_valid):
# calculate otsu_threshold as lower limit. Otsu understimates the threshold.
try:
otsu_thresh = skf.threshold_otsu(pix_valid)
except:
return np.nan
# calculate the histogram
pix_hist = np.bincount(pix_valid)
# the higher limit is the most frequent value in the distribution
# (background)
largest_peak = np.argmax(pix_hist)
if otsu_thresh < largest_peak and otsu_thresh + 2 < len(pix_hist) - 1:
# smooth the histogram to find a better threshold
pix_hist = np.convolve(pix_hist, np.ones(3), 'same')
cumhist = np.cumsum(pix_hist)
xx = np.arange(otsu_thresh, cumhist.size)
try: