def get_n_masks(im,z):
coords = []
binary = im < 604
cleared = clear_border(binary)
label_image = label(cleared)
areas = [r.area for r in regionprops(label_image)]
areas.sort()
if len(areas) > 2:
for region in regionprops(label_image):
if region.area < 6 and region.area > 3:
# print(region.centroid)
# print(region.area)
centroid = region.centroid
coord = [int(centroid[0]),int(centroid[1]),z]
# plot_im(im,centroid)
coords.append(coord)
return coords
python类label()的实例源码
def remove_conn_components(pred_mask, num_cc):
labels = label(pred_mask)
if num_cc == 1:
maxArea = 0
for region in regionprops(labels):
if region.area > maxArea:
maxArea = region.area
print(maxArea)
mask = remove_small_objects(labels, maxArea - 1)
else:
mask = remove_small_objects(labels, 3000, connectivity=2)
return mask
def keep_largest_connected_components(mask):
'''
Keeps only the largest connected components of each label for a segmentation mask.
'''
out_img = np.zeros(mask.shape, dtype=np.uint8)
for struc_id in [1, 2, 3]:
binary_img = mask == struc_id
blobs = measure.label(binary_img, connectivity=1)
props = measure.regionprops(blobs)
if not props:
continue
area = [ele.area for ele in props]
largest_blob_ind = np.argmax(area)
largest_blob_label = props[largest_blob_ind].label
out_img[blobs == largest_blob_label] = struc_id
return out_img
def plot_regions(self, fill=True, bgimage=None, alpha=0.5):
import pylab as pl
ax = pl.gca()
assert isinstance(ax, pl.Axes)
colors = i12.JET_12
self._plot_background(bgimage)
for label in self.regions:
color = colors[i12.LABELS.index(label)] / 255.
for region in self.regions[label]:
t = region['top']
l = self.facade_left + region['left']
b = region['bottom']
r = self.facade_left + region['right']
patch = pl.Rectangle((l, t), r - l, b - t, color=color, fill=fill, alpha=alpha)
ax.add_patch(patch)
def convert_new(fname, target_size):
print('Processing image: %s' % fname)
img = Image.open(fname)
blurred = img.filter(ImageFilter.BLUR)
ba = np.array(blurred)
ba_gray = rgb2gray(ba)
val = filters.threshold_otsu(ba_gray)
# foreground = (ba_gray > val).astype(np.uint8)
foreground = closing(ba_gray > val, square(3))
# kernel = morphology.rectangle(5, 5)
# foreground = morphology.binary_dilation(foreground, kernel)
labels = measure.label(foreground)
properties = measure.regionprops(labels)
properties = sorted(properties, key=lambda p: p.area, reverse=True)
# draw_top_regions(properties, 3)
# return ba
bbox = properties[0].bbox
bbox = (bbox[1], bbox[0], bbox[3], bbox[2])
cropped = img.crop(bbox)
resized = cropped.resize([target_size, target_size])
return np.array(resized)
def convert_new_regions(fname, target_size):
print('Processing image: %s' % fname)
img = Image.open(fname)
blurred = img.filter(ImageFilter.BLUR)
ba = np.array(blurred)
ba_gray = rgb2gray(ba)
val = filters.threshold_otsu(ba_gray)
# foreground = (ba_gray > val).astype(np.uint8)
foreground = closing(ba_gray > val, square(3))
# kernel = morphology.rectangle(5, 5)
# foreground = morphology.binary_dilation(foreground, kernel)
labels = measure.label(foreground)
properties = measure.regionprops(labels)
properties = sorted(properties, key=lambda p: p.area, reverse=True)
draw_top_regions(properties, 3)
return ba
def convert(fname, target_size):
# print('Processing image: %s' % fname)
img = Image.open(fname)
blurred = img.filter(ImageFilter.BLUR)
ba = np.array(blurred)
ba_gray = rgb2gray(ba)
val = filters.threshold_otsu(ba_gray)
# foreground = (ba_gray > val).astype(np.uint8)
foreground = closing(ba_gray > val, square(3))
# kernel = morphology.rectangle(5, 5)
# foreground = morphology.binary_dilation(foreground, kernel)
labels = measure.label(foreground)
properties = measure.regionprops(labels)
properties = sorted(properties, key=lambda p: p.area, reverse=True)
# draw_top_regions(properties, 3)
# return ba
bbox = properties[0].bbox
bbox = (bbox[1], bbox[0], bbox[3], bbox[2])
cropped = img.crop(bbox)
resized = cropped.resize([target_size, target_size])
return resized
testEstsMask.py 文件源码
项目:Human-Pose-Estimation-Using-FCN
作者: jessiechouuu
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
def createMask(originalMap , alpha):
height,width = originalMap.shape;
threshold = alpha * np.amax(originalMap)
# im2bw
bw = np.zeros((height,width))
idx = originalMap > threshold
bw[idx] = 1
location = np.argmax(originalMap)
[row,col] = np.unravel_index(location,(height,width))
blobs = bw==1
ConnectedComponent = measure.label(blobs)
CompLabel = ConnectedComponent[row,col]
PixelList = ConnectedComponent==CompLabel
mask = np.ones((height,width));
mask[PixelList] = 0;
return mask
def _floodfill(self, img):
back = Back._scharr(img)
# Binary thresholding.
back = back > 0.05
# Thin all edges to be 1-pixel wide.
back = skm.skeletonize(back)
# Edges are not detected on the borders, make artificial ones.
back[0, :] = back[-1, :] = True
back[:, 0] = back[:, -1] = True
# Label adjacent pixels of the same color.
labels = label(back, background=-1, connectivity=1)
# Count as background all pixels labeled like one of the corners.
corners = [(1, 1), (-2, 1), (1, -2), (-2, -2)]
for l in (labels[i, j] for i, j in corners):
back[labels == l] = True
# Remove remaining inner edges.
return skm.opening(back)
def create_mask(im_arr, erode=0):
if im_arr.shape[2] == 3:
im_arr = rgb2gray(im_arr)
thresh = 0.05
inv_bin = np.invert(im_arr > thresh)
all_labels = measure.label(inv_bin)
# Select largest object and invert
seg_arr = all_labels == 0
if erode > 0:
strel = selem.disk(erode, dtype=np.bool)
seg_arr = binary_erosion(seg_arr, selem=strel)
elif erode < 0:
strel = selem.disk(abs(erode), dtype=np.bool)
seg_arr = binary_dilation(seg_arr, selem=strel)
return seg_arr.astype(np.bool)
def generate_markers(image):
#Creation of the internal Marker
marker_internal = image < -400
marker_internal = segmentation.clear_border(marker_internal)
marker_internal_labels = measure.label(marker_internal)
areas = [r.area for r in measure.regionprops(marker_internal_labels)]
areas.sort()
if len(areas) > 2:
for region in measure.regionprops(marker_internal_labels):
if region.area < areas[-2]:
for coordinates in region.coords:
marker_internal_labels[coordinates[0], coordinates[1]] = 0
marker_internal = marker_internal_labels > 0
#Creation of the external Marker
external_a = ndimage.binary_dilation(marker_internal, iterations=10)
external_b = ndimage.binary_dilation(marker_internal, iterations=55)
marker_external = external_b ^ external_a
#Creation of the Watershed Marker matrix
marker_watershed = np.zeros(image.shape, dtype=np.int)
marker_watershed += marker_internal * 255
marker_watershed += marker_external * 128
return marker_internal, marker_external, marker_watershed
def generate_markers(image):
#Creation of the internal Marker
marker_internal = image < -400
marker_internal = segmentation.clear_border(marker_internal)
marker_internal_labels = measure.label(marker_internal)
areas = [r.area for r in measure.regionprops(marker_internal_labels)]
areas.sort()
if len(areas) > 2:
for region in measure.regionprops(marker_internal_labels):
if region.area < areas[-2]:
for coordinates in region.coords:
marker_internal_labels[coordinates[0], coordinates[1]] = 0
marker_internal = marker_internal_labels > 0
#Creation of the external Marker
external_a = ndimage.binary_dilation(marker_internal, iterations=10)
external_b = ndimage.binary_dilation(marker_internal, iterations=55)
marker_external = external_b ^ external_a
#Creation of the Watershed Marker matrix
marker_watershed = np.zeros(image.shape, dtype=np.int)
marker_watershed += marker_internal * 255
marker_watershed += marker_external * 128
return marker_internal, marker_external, marker_watershed
def generate_markers(image):
#Creation of the internal Marker
marker_internal = image < -400
marker_internal = segmentation.clear_border(marker_internal)
marker_internal_labels = measure.label(marker_internal)
areas = [r.area for r in measure.regionprops(marker_internal_labels)]
areas.sort()
if len(areas) > 2:
for region in measure.regionprops(marker_internal_labels):
if region.area < areas[-2]:
for coordinates in region.coords:
marker_internal_labels[coordinates[0], coordinates[1]] = 0
marker_internal = marker_internal_labels > 0
#Creation of the external Marker
external_a = ndimage.binary_dilation(marker_internal, iterations=10)
external_b = ndimage.binary_dilation(marker_internal, iterations=55)
marker_external = external_b ^ external_a
#Creation of the Watershed Marker matrix
marker_watershed = np.zeros(image.shape, dtype=np.int)
marker_watershed += marker_internal * 255
marker_watershed += marker_external * 128
return marker_internal, marker_external, marker_watershed
def findMaximaOnFG(self, param):
self.defineFG(param)
#self.smooth_corr()
self.coorExtract = [0, 0]
xmin, ymin = self.coorExtract
img=self.candi
img [self.FG ==0] =0
im = img_as_float(img)
image_max = ndimage.maximum_filter(im, size=10, mode='constant')
coordinates = peak_local_max(im, min_distance=10)
tep=np.zeros(self.candi.shape)
for i,ide in enumerate(coordinates):
tep[ide[0],ide[1]] = self.candi[ide[0],ide[1]]
lbl = ndimage.label(tep)[0]
centerc = np.round(ndimage.measurements.center_of_mass(tep, lbl, range(1,np.max(lbl)+1)))
if centerc.size > 0:
self.centersX = centerc[:,0].astype(int)
self.centersY = centerc[:,1].astype(int)
self.nComponents = len(self.centersX)
def generate_markers_3d(image):
#Creation of the internal Marker
marker_internal = image < -400
marker_internal_labels = np.zeros(image.shape).astype(np.int16)
for i in range(marker_internal.shape[0]):
marker_internal[i] = segmentation.clear_border(marker_internal[i])
marker_internal_labels[i] = measure.label(marker_internal[i])
#areas = [r.area for r in measure.regionprops(marker_internal_labels)]
areas = [r.area for i in range(marker_internal.shape[0]) for r in measure.regionprops(marker_internal_labels[i])]
for i in range(marker_internal.shape[0]):
areas = [r.area for r in measure.regionprops(marker_internal_labels[i])]
areas.sort()
if len(areas) > 2:
for region in measure.regionprops(marker_internal_labels[i]):
if region.area < areas[-2]:
for coordinates in region.coords:
marker_internal_labels[i, coordinates[0], coordinates[1]] = 0
marker_internal = marker_internal_labels > 0
#Creation of the external Marker
# 3x3 structuring element with connectivity 1, used by default
struct1 = ndimage.generate_binary_structure(2, 1)
struct1 = struct1[np.newaxis,:,:] # expand by z axis .
external_a = ndimage.binary_dilation(marker_internal, structure=struct1, iterations=10)
external_b = ndimage.binary_dilation(marker_internal, structure=struct1, iterations=55)
marker_external = external_b ^ external_a
#Creation of the Watershed Marker matrix
#marker_watershed = np.zeros((512, 512), dtype=np.int) # origi
marker_watershed = np.zeros((marker_external.shape), dtype=np.int)
marker_watershed += marker_internal * 255
marker_watershed += marker_external * 128
return marker_internal, marker_external, marker_watershed
def generate_markers_3d(image):
#Creation of the internal Marker
marker_internal = image < -400
marker_internal_labels = np.zeros(image.shape).astype(np.int16)
for i in range(marker_internal.shape[0]):
marker_internal[i] = segmentation.clear_border(marker_internal[i])
marker_internal_labels[i] = measure.label(marker_internal[i])
#areas = [r.area for r in measure.regionprops(marker_internal_labels)]
areas = [r.area for i in range(marker_internal.shape[0]) for r in measure.regionprops(marker_internal_labels[i])]
for i in range(marker_internal.shape[0]):
areas = [r.area for r in measure.regionprops(marker_internal_labels[i])]
areas.sort()
if len(areas) > 2:
for region in measure.regionprops(marker_internal_labels[i]):
if region.area < areas[-2]:
for coordinates in region.coords:
marker_internal_labels[i, coordinates[0], coordinates[1]] = 0
marker_internal = marker_internal_labels > 0
#Creation of the external Marker
# 3x3 structuring element with connectivity 1, used by default
struct1 = ndimage.generate_binary_structure(2, 1)
struct1 = struct1[np.newaxis,:,:] # expand by z axis .
external_a = ndimage.binary_dilation(marker_internal, structure=struct1, iterations=10)
external_b = ndimage.binary_dilation(marker_internal, structure=struct1, iterations=55)
marker_external = external_b ^ external_a
#Creation of the Watershed Marker matrix
#marker_watershed = np.zeros((512, 512), dtype=np.int) # origi
marker_watershed = np.zeros((marker_external.shape), dtype=np.int)
marker_watershed += marker_internal * 255
marker_watershed += marker_external * 128
return marker_internal, marker_external, marker_watershed
def clean_contour(in_contour, is_prob=False):
if is_prob:
pred = (in_contour >= 0.5).astype(np.float32)
else:
pred = in_contour
labels = measure.label(pred)
area = []
for l in range(1, np.amax(labels) + 1):
area.append(np.sum(labels == l))
out_contour = in_contour
out_contour[np.logical_and(labels > 0, labels != np.argmax(area) + 1)] = 0
return out_contour
def img_recover(data, label, imgsize=(200, 200), px_over=5):
"""Recover the image after classification.
Inputs
======
data: np.ndarray
the splitted samples data of the observation
label: np.ndarray
the estimated labels
imgsize: tuple
shape of the image
px_over: integer
the overlapped pixels
Output
======
img: np.ndarray
the recovered image
"""
# Init
img = np.zeros(imgsize, dtype=bool)
# Get params
numsamples, boxsize = data.shape
boxsize = int(np.sqrt(boxsize))
# Number of boxes
px_diff = boxsize - px_over
box_rows = int(np.round((imgsize[0] - boxsize - 1) / px_diff)) + 1
box_cols = int(np.round((imgsize[1] - boxsize - 1) / px_diff)) + 1
# recover
for i in range(box_rows):
for j in range(box_cols):
if label[i*box_rows+j] == 1:
label_temp = True
else:
label_temp = False
img[i * px_diff:i * px_diff + boxsize,
j * px_diff:j * px_diff + boxsize] += label_temp
return img.astype(int)
def clean_contour(prob, c_input):
# Smaller areas with lower prob are very likely to be false positives
wt_mor = binary_dilation((c_input > 0).astype(np.float32), iterations=10)
labels = measure.label(wt_mor)
w_area = []
for l in range(1, np.amax(labels) + 1):
w_area.append(np.sum(prob[labels == l]))
if len(w_area) > 0:
max_area = np.amax(w_area)
for l in range(len(w_area)):
if w_area[l] < max_area / 2.0:
c_input[labels == l + 1] = 0
return c_input
def get_segmented_lungs(im, plot=False):
# Step 1: Convert into a binary image.
binary = im < -400
# Step 2: Remove the blobs connected to the border of the image.
cleared = clear_border(binary)
# Step 3: Label the image.
label_image = label(cleared)
# Step 4: Keep the labels with 2 largest areas.
areas = [r.area for r in regionprops(label_image)]
areas.sort()
if len(areas) > 2:
for region in regionprops(label_image):
if region.area < areas[-2]:
for coordinates in region.coords:
label_image[coordinates[0], coordinates[1]] = 0
binary = label_image > 0
# Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
selem = disk(2)
binary = binary_erosion(binary, selem)
# Step 6: Closure operation with a disk of radius 10. This operation is to keep nodules attached to the lung wall.
selem = disk(10) # CHANGE BACK TO 10
binary = binary_closing(binary, selem)
# Step 7: Fill in the small holes inside the binary mask of lungs.
edges = roberts(binary)
binary = ndi.binary_fill_holes(edges)
# Step 8: Superimpose the binary mask on the input image.
get_high_vals = binary == 0
im[get_high_vals] = -2000
return im, binary
def extract_boxes_as_dictionaries(image, threshold=0.5, se=disk(3)):
mask = image > threshold
mask = binary_opening(mask, selem=se)
try:
props = regionprops(label(mask))
def _tag(tlbr):
t, l, b, r = tlbr
return dict(top=int(t), left=int(l), bottom=int(b), right=int(r))
result = [_tag(r.bbox) for r in props]
except (ValueError, TypeError) as e:
result = []
return result
def get_mask(image, uid):
mask = np.array(image > -320, dtype=np.int8)
# Set the edges to zeros. This is to connect the air regions, which
# may appear separated in some scans
mask[:, 0] = 0
mask[:, -1] = 0
mask[:, :, 0] = 0
mask[:, :, -1] = 0
labels = measure.label(mask, connectivity=1, background=-1)
vals, counts = np.unique(labels, return_counts=True)
inds = np.argsort(counts)
# Assume that the lungs make up the third largest region
lung_val = vals[inds][-3]
if mask[labels == lung_val].sum() != 0:
print('Warning: could not get mask for %s' % uid)
mask[:] = 1
return mask
mask[labels == lung_val] = 1
mask[labels != lung_val] = 0
fill_mask(mask)
left_center = mask[mask.shape[0] // 2, mask.shape[1] // 2, mask.shape[2] // 4]
right_center = mask[mask.shape[0] // 2, mask.shape[1] // 2, mask.shape[2] * 3 // 4]
if (left_center == 0) or (right_center == 0):
print('Warning: could not get mask for %s' % uid)
mask[:] = 1
return mask
mask = ndimage.morphology.binary_dilation(mask, iterations=settings.mask_dilation)
return mask
def fill_mask_slice(slc):
labels = measure.label(slc, connectivity=1, background=-1)
vals, counts = np.unique(labels, return_counts=True)
inds = np.argsort(counts)
max_val = vals[inds][-1]
if len(vals) > 1:
next_val = vals[inds][-2]
labels[labels == next_val] = max_val
slc[labels != max_val] = 1
def segment_lung_mask(image, fill_lung_structures=True):
# not actually binary, but 1 and 2.
# 0 is treated as background, which we do not want
binary_image = np.array(image > -320, dtype=np.int8)+1
labels = measure.label(binary_image)
# Pick the pixel in the very corner to determine which label is air.
# Improvement: Pick multiple background labels from around the patient
# More resistant to "trays" on which the patient lays cutting the air
# around the person in half
background_label = labels[0,0,0]
#Fill the air around the person
binary_image[background_label == labels] = 2
# Method of filling the lung structures (that is superior to something like
# morphological closing)
if fill_lung_structures:
# For every slice we determine the largest solid structure
for i, axial_slice in enumerate(binary_image):
axial_slice = axial_slice - 1
labeling = measure.label(axial_slice)
l_max = largest_label_volume(labeling, bg=0)
if l_max is not None: #This slice contains some lung
binary_image[i][labeling != l_max] = 1
binary_image -= 1 #Make the image actual binary
binary_image = 1-binary_image # Invert it, lungs are now 1
# Remove other air pockets insided body
labels = measure.label(binary_image, background=0)
l_max = largest_label_volume(labels, bg=0)
if l_max is not None: # There are air pockets
binary_image[labels != l_max] = 0
return binary_image
def extract_voxels(images,pred_1,truths=None):
eroded = morphology.erosion(pred_1,np.ones([3,3,3]))
dilation = morphology.dilation(eroded,np.ones([3,3,3]))
labels = measure.label(dilation) # Different labels are displayed in different colors
label_vals = np.unique(labels)
regions = measure.regionprops(labels)
kept = 0
removed = 0
data = []
for idx in range(len(regions)):
b = regions[idx].bbox
if regions[idx].area < 50:
removed += 1
continue
kept += 1
print "before->",b
b = get_bounding_box(b,images.shape)
print "after->",b
image_voxel = images[b[0]:b[3],b[1]:b[4],b[2]:b[5]]
label = 0
if not truths is None:
print "finding region in truths"
truth_voxel = truths[b[0]:b[3],b[1]:b[4],b[2]:b[5]]
nonzeros = np.count_nonzero(truth_voxel)
if nonzeros > 0:
label = 1
assert(image_voxel.size==(VOXEL_DEPTH*VOXEL_DEPTH*VOXEL_DEPTH))
print "Appending voxel with label ",label
data.append((image_voxel,label,b))
print "kept",kept,"removed",removed
sys.stdout.flush()
return data
def image_filter(img):
img2 = img.copy();
img2[img2 < 30] = 100;
img2 = exp.smooth_image(img2, sigma = 1.0);
#plt.figure(6); plt.clf();
#plt.imshow(img2);
# threshold image and take zero smaller components..
th = img2 < 92;
th2 = morph.binary_closing(th, morph.diamond(1))
label = meas.label(th2, background=0)
#plt.imshow(mask)
bs = meas.regionprops(label+1);
area = np.array([prop.area for prop in bs]);
if len(area) > 0:
mask = np.logical_and(label > -1, label != np.argsort(area)[-1]);
img2[mask] = 100;
img2[:2,:] = 100; img2[-2:,:] = 100;
img2[:,:2] = 100; img2[:,-2:] = 100;
#plt.figure(6); plt.clf();
#plt.subplot(1,2,1);
#plt.imshow(img2, vmin = 84, vmax = 92, cmap = plt.cm.gray)
#plt.subplot(1,2,2);
#plt.imshow(img2);
return img2;
def image_filter(img):
img2 = img.copy();
img2[img2 < 30] = 100;
img2 = exp.smooth_image(img2, sigma = 1.0);
#plt.figure(6); plt.clf();
#plt.imshow(img2);
# threshold image and take zero smaller components..
th = img2 < 92;
th2 = morph.binary_closing(th, morph.diamond(1))
label = meas.label(th2, background=0)
#plt.imshow(mask)
bs = meas.regionprops(label+1);
area = np.array([prop.area for prop in bs]);
if len(area) > 0:
mask = np.logical_and(label > -1, label != np.argsort(area)[-1]);
img2[mask] = 100;
img2[:2,:] = 100; img2[-2:,:] = 100;
img2[:,:2] = 100; img2[:,-2:] = 100;
#plt.figure(6); plt.clf();
#plt.subplot(1,2,1);
#plt.imshow(img2, vmin = 84, vmax = 92, cmap = plt.cm.gray)
#plt.subplot(1,2,2);
#plt.imshow(img2);
return img2;
def localization(x, y):
"""Simple post-processing and get IVDs positons.
Return:
positons: calculated by `ndimage.measurements.center_of_mass`
y: after fill holes and remove small objects.
"""
labels, nums = label(y, return_num=True)
areas = np.array([prop.filled_area for prop in regionprops(labels)])
assert nums >= 7, 'Fail in this test, should detect at least seven regions.'
# Segment a joint region which should be separate (if any).
while np.max(areas) > 10000:
y = ndimage.binary_opening(y, structure=np.ones((3, 3, 3)))
areas = np.array([prop.filled_area for prop in regionprops(label(y))])
# Remove small objects.
threshold = sorted(areas, reverse=True)[7]
y = morphology.remove_small_objects(y, threshold + 1)
# Fill holes.
y = ndimage.binary_closing(y, structure=np.ones((3, 3, 3)))
y = morphology.remove_small_holes(y, min_size=512, connectivity=3)
positions = ndimage.measurements.center_of_mass(x, label(y), range(1, 8))
return np.array(positions), y
def segment_lung_mask(image, fill_lung_structures=True):
# not actually binary, but 1 and 2.
# 0 is treated as background, which we do not want
binary_image = np.array(image > -320, dtype=np.int8)+1
labels = measure.label(binary_image)
# Pick the pixel in the very corner to determine which label is air.
# Improvement: Pick multiple background labels from around the patient
# More resistant to "trays" on which the patient lays cutting the air
# around the person in half
background_label = labels[0,0,0]
#Fill the air around the person
binary_image[background_label == labels] = 2
# Method of filling the lung structures (that is superior to something like
# morphological closing)
if fill_lung_structures:
# For every slice we determine the largest solid structure
for i, axial_slice in enumerate(binary_image):
axial_slice = axial_slice - 1
labeling = measure.label(axial_slice)
l_max = largest_label_volume(labeling, bg=0)
if l_max is not None: #This slice contains some lung
binary_image[i][labeling != l_max] = 1
binary_image -= 1 #Make the image actual binary
binary_image = 1-binary_image # Invert it, lungs are now 1
# Remove other air pockets insided body
labels = measure.label(binary_image, background=0)
l_max = largest_label_volume(labels, bg=0)
if l_max is not None: # There are air pockets
binary_image[labels != l_max] = 0
return binary_image
def analyze(tgt, idx):
print "%d :==========================" % idx
tgt = binarize(tgt)
if should_invert(tgt):
tgt = invert(tgt)
regions = regionprops(label(tgt))
for region in regions:
print "-----"
print "area:%s" % region.area # ???????????
print "centroid:" + str(region.centroid) # ????
print "perimeter:%s" % region.perimeter # ??
print "euler:%s" % region.euler_number
print "circularity:%s" % (region.area / region.perimeter**2)
print "complexity:%s" % (region.perimeter**2 / region.area)