Skip to content

simple code suggestions to improve #50

@hvgazula

Description

@hvgazula

pixel_counts = {label:count for label,count in zip(unique,counts)}

dict(zip(unique,count))

https://github.com/sabeenlohawala/tissue_labeling/blob/8611ada4596771e1ab25cb02faf7be557509593b/scripts/mit_kwyk_data.py#L180C1-L181C85

shapes, pixel_counts = zip(*shapes_and_pixel_counts)

for i in range(label_vol.shape[d]):
# get the slice
if d == 0:
feature_slice = feature_vol[i, :, :]
label_slice = label_vol[i, :, :]
elif d == 1:
feature_slice = feature_vol[:, i, :]
label_slice = label_vol[:, i, :]
elif d == 2:
feature_slice = feature_vol[:, :, i]
label_slice = label_vol[:, :, i]
# discard slices with < 20% brain (> 80% background)
count_background = np.sum(label_slice == 0)
if count_background > 0.8 * (label_slice.shape[0] * label_slice.shape[1]):
continue
# pad slices
pad_rows = max(0,max_shape[0] - label_slice.shape[0])
pad_cols = max(0,max_shape[1] - label_slice.shape[1])
# padding for each side
pad_top = pad_rows // 2
pad_bottom = pad_rows - pad_top
pad_left = pad_cols // 2
pad_right = pad_cols - pad_left
padded_feature_slice = np.pad(feature_slice, ((pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=0)
padded_label_slice = np.pad(label_slice, ((pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=0)
# save .npy files
feature_slice_filename = f"{os.path.basename(feature).split('.')[0]}_{slice_idx:03d}.npy"
label_slice_filename = f"{os.path.basename(label).split('.')[0]}_{slice_idx:03d}.npy"
np.save(os.path.join(feature_slice_dest_dir,feature_slice_filename), padded_feature_slice[np.newaxis,:])
np.save(os.path.join(label_slice_dest_dir,label_slice_filename), padded_label_slice[np.newaxis,:])
# Done: get pixel_counts
if get_pixel_counts:
unique,counts = np.unique(padded_label_slice,return_counts = True)
pixel_counts.update({label:count for label,count in zip(unique,counts)})
# increase slice_idx
slice_idx += 1

Run this example and tell me if the above cannot be improved in the same way

import numpy as np
a = np.random.rand(10, 5, 3)
b  = list(map(sum, a)  # sum can be any function
print(len(b), b[0].shape)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions