Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def doTest(file_name,model):
probs,img_arr=seg(opt.img_dir+file_name,model)
probs=probs>opt.prob_threshould
probs=morphology.dilation(probs,np.ones([3,3,3]))
probs=morphology.dilation(probs,np.ones([3,3,3]))
probs=morphology.erosion(probs,np.ones([3,3,3]))
#np.save("probs.npy",probs)
labels = measure.label(probs,connectivity=2)
#label_vals = np.unique(labels)
regions = measure.regionprops(labels)
centers = []
crops = []
bboxes = []
spans=[]
for prop in regions:
B = prop.bbox
if B[3]-B[0]>2 and B[4]-B[1]>4 and B[5]-B[2]>4:
z=int((B[3]+B[0])/2.0)
y=int((B[4]+B[1])/2.0)
x=int((B[5]+B[2])/2.0)
span=np.array([int(B[3]-B[0]),int(B[4]-B[1]),int(B[5]-B[2])])
spans.append(span)
centers.append(np.array([z,y,x]))
bboxes.append(B)
bestScore = 0
bestLayoutIndex = 4
for layoutIndex in xrange(3, 6):
score = np.logical_and(mask, layout_gt == layoutIndex).sum()
if score > bestScore:
bestLayoutIndex = layoutIndex
bestScore = score
pass
continue
layout_pred[mask] = bestLayoutIndex
pass
emptyMask = layout_pred == 0
if emptyMask.sum() > 0:
print(index, emptyMask.sum())
masks = measure.label(emptyMask, background=0)
for maskIndex in xrange(masks.min() + 1, masks.max() + 1):
mask = masks == maskIndex
bestScore = 0
bestLayoutIndex = 4
for layoutIndex in xrange(1, 6):
score = np.logical_and(mask, layout_gt == layoutIndex).sum()
if score > bestScore:
bestLayoutIndex = layoutIndex
bestScore = score
pass
continue
layout_pred[mask] = bestLayoutIndex
continue
pass
layout_pred_img = drawSegmentationImage(layout_pred, blackIndex=0)
def binary_mask_to_polygon(binary_mask, tolerance=0):
"""Converts a binary mask to COCO polygon representation
Args:
binary_mask: a 2D binary numpy array where '1's represent the object
tolerance: Maximum distance from original points of polygon to approximated
polygonal chain. If tolerance is 0, the original coordinate array is returned.
"""
polygons = []
# pad mask to close contours of shapes which start and end at an edge
padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
contours = measure.find_contours(padded_binary_mask, 0.5)
contours = np.subtract(contours, 1)
for contour in contours:
contour = PycocoCreatorTools.close_contour(contour)
contour = measure.approximate_polygon(contour, tolerance)
if len(contour) < 3:
continue
contour = np.flip(contour, axis=1)
segmentation = contour.ravel().tolist()
# after padding and subtracting 1 we may get -0.5 points in our segmentation
segmentation = [0 if i < 0 else i for i in segmentation]
polygons.append(segmentation)
return polygons
def find_centroids(label_image):
input_props = skimage.measure.regionprops(
label_image, intensity_image=None, cache=True
)
input_centroids = [numpy.int_(obj["centroid"]) for obj in input_props]
output_segmented = numpy.zeros_like(label_image)
for ind, arr in enumerate(input_centroids):
output_segmented[tuple(arr)] = ind + 1
return output_segmented
def xy(self):
if self._xy is None:
if self.remove_background:
img = self.img_corr
else:
img = self.img
bg = ndimage.gaussian_filter(img, self.sigmin) - ndimage.gaussian_filter(img, self.sigmax)
labels, numlabels = ndimage.label(bg > self.threshold)
labels = morphology.remove_small_objects(labels, self.nmin)
props = measure.regionprops(labels, img)
self._xy = np.array([prop.centroid for prop in props])
return self._xy
# dilate sink image
Dilated = mp.binary_dilation(SeedImage, mp.disk(Radius))
# generate new labels for merged seeds, define memberships
Labels = ms.label(Dilated)
New = Labels[Sinks[:, 1].astype(np.int), Sinks[:, 0].astype(np.int)]
# get unique list of seed clusters
Unique = np.arange(1, New.max()+1)
# generate new seed list
Merged = np.zeros(Label.shape)
# get pixel list for each sink object
Props = ms.regionprops(Label.astype(np.int))
# fill in new values
for i in Unique:
Indices = np.nonzero(New == i)[0]
for j in Indices:
Coords = Props[j].coords
Merged[Coords[:, 0], Coords[:, 1]] = i
return Merged
new_height, new_width = int(image.shape[0] * resize_factor), int(image.shape[1] * resize_factor)
image = ia.imresize_single_image(image, (new_height, new_width), interpolation=self.interpolation)
#image_sp = np.random.randint(0, 255, size=image.shape).astype(np.uint8)
image_sp = np.copy(image)
#time_start = time.time()
segments = segmentation.slic(image, n_segments=n_segments_samples[i], compactness=10)
#print("seg", np.min(segments), np.max(segments), n_segments_samples[i])
#print("segmented in %.4fs" % (time.time() - time_start))
#print(np.bincount(segments.flatten()))
#time_start = time.time()
nb_channels = image.shape[2]
for c in sm.xrange(nb_channels):
# segments+1 here because otherwise regionprops always misses
# the last label
regions = measure.regionprops(segments+1, intensity_image=image[..., c])
for ridx, region in enumerate(regions):
# with mod here, because slic can sometimes create more superpixel
# than requested. replace_samples then does not have enough
# values, so we just start over with the first one again.
if replace_samples[ridx % len(replace_samples)] == 1:
#print("changing region %d of %d, channel %d, #indices %d" % (ridx, np.max(segments), c, len(np.where(segments == ridx)[0])))
mean_intensity = region.mean_intensity
image_sp_c = image_sp[..., c]
image_sp_c[segments == ridx] = mean_intensity
#print("colored in %.4fs" % (time.time() - time_start))
if orig_shape != image.shape:
image_sp = ia.imresize_single_image(image_sp, orig_shape[0:2], interpolation=self.interpolation)
images[i] = image_sp
return images
# Estimated glint diameter in pixels
glint_d = int(cfg.getfloat('PUPILSEG','glintdiameterperc') * nx / 100.0)
# Glint diameter should be >= 1 pixel
if glint_d < 1:
glint_d = 1
# Reasonable upper and lower bounds on glint area (x3, /3)
glint_A = np.pi * (glint_d / 2.0)**2
A_min, A_max = glint_A / 3.0, glint_A * 3.0
# Find bright pixels in full scale uint8 image (ie value > 250)
bright = np.uint8(roi > 250)
# Label connected regions (blobs)
bright_labels = measure.label(bright)
# Get region properties for all bright blobs in mask
bright_props = measure.regionprops(bright_labels)
# Init glint parameters
r_min = np.Inf
glint_label = -1
glint = (np.nan, np.nan)
glint_mask = np.zeros_like(roi, dtype="uint8")
roi_noglint = roi.copy()
# Find closest blob to ROI center within glint area range
for props in bright_props:
# Blob area in pixels^2
A = props.area
def compare_measure(val_gt, output, args):
y_output = skimage.color.rgb2ycbcr(output)
y_gt = skimage.color.rgb2ycbcr(val_gt)
y_output = y_output / 255.0
y_gt = y_gt / 255.0
y_psnr = skimage.measure.compare_psnr(y_output[args.scale:-args.scale, args.scale:-args.scale, :1], y_gt[args.scale:-args.scale, args.scale:-args.scale, :1], data_range = 1.0)
y_ssim = compare_ssim(y_output[args.scale:-args.scale, args.scale:-args.scale, 0], y_gt[args.scale:-args.scale, args.scale:-args.scale, 0], gaussian_weights=True, use_sample_covariance=False, data_range = 1.0)
return y_psnr, y_ssim
def marching_cubes(self, tsdf = None, step_size = 0):
if step_size < 1:
step_size = self._marching_cubes_step_size
if tsdf is not None:
return measure.marching_cubes_lewiner(tsdf,
step_size = step_size,
allow_degenerate=False)
self._vertices, self._faces, self._normals, values = measure.marching_cubes_lewiner(self._tsdf,
step_size = step_size,
allow_degenerate=False)
if self._verbose:
print("Marching Cubes result: number of extracted vertices is %d" % (len(self._vertices)))