def build_annotated(self):
     thumb = create_section_image(self.section, self.experiment_id,
                                  self.directory, self.full_data,
                                  self.bboxes)
     _, r, _ = detect_brain(cv2.cvtColor(thumb, cv2.COLOR_BGR2GRAY))
     cv2.imwrite(self.annotated_url, thumb[r.y:r.y + r.h,
                                           r.x:r.x + r.w])
    def calculate_global_parameters(self, density3d_maps, dense_masks, cells):
        relevant_sections = cells.section.unique()
        relevant_sections.sort()
        globs_per_section = infinite_dict()
        for section in relevant_sections:
            self.logger.debug(f"Calculating globals for section {section} of {self.id}...")
            section_seg_data = self.seg_data[:, :, section]
            for region, (start, end, shape, (mask_y, mask_x, mask_section)) in dense_masks.items():
                if start <= section <= end:
                    if shape[0] < section_seg_data.shape[0]:
                        ratio = section_seg_data.shape[0] // shape[0]
                        deltas_x = np.array(([i for i in range(ratio)] * ratio) * len(mask_x))
                        deltas_y = np.array([[i] * ratio for i in range(ratio)] * len(mask_x))
                        mask_y = np.kron(mask_y * ratio, np.ones((1, ratio * ratio))).flatten() + deltas_y
                        mask_x = np.kron(mask_x * ratio, np.ones((1, ratio * ratio))).flatten() + deltas_x
                    elif shape[0] > section_seg_data.shape[0]:
                        ratio = shape[0] // section_seg_data.shape[0]
                        section_seg_data = np.kron(section_seg_data,
                                                   np.ones((ratio, ratio), dtype=section_seg_data.dtype))

                    relevant_cells = mask_section == (section - start)
                    section_seg_data[mask_y[relevant_cells], mask_x[relevant_cells]] = region

            section_density_map = density3d_maps[2][:, :, section - density3d_maps[0]]

            if section_density_map.shape[0] > section_seg_data.shape[0]:
                ratio = section_density_map.shape[0] // section_seg_data.shape[0]
                section_seg_data = np.kron(section_seg_data, np.ones((ratio, ratio), dtype=section_seg_data.dtype))
            elif section_density_map.shape[0] < section_seg_data.shape[0]:
                ratio = section_seg_data.shape[0] // section_density_map.shape[0]
                section_density_map = np.kron(section_density_map,
                                              np.ones((ratio, ratio), dtype=section_density_map.dtype))

            _, bbox, _ = detect_brain((section_seg_data != 0).astype(np.uint8) * 255)
            center_x = bbox.x + bbox.w // 2
            scale_factor = (0.35 * 64) / (section_seg_data.shape[0] / self.seg_data.shape[0])
            relevant_regions = np.intersect1d(np.unique(section_seg_data),
                                              cells[cells.section == section].structure_id.unique())
            for region in relevant_regions:
                region_cells = np.where(section_seg_data == region)
                globs_per_section[region][section]['region_area'] = region_cells[0].shape[0] * (scale_factor ** 2)
                globs_per_section[region][section]['region_area_left'] = np.where(region_cells[1] < center_x)[0].shape[
                                                                             0] * (
                                                                                 scale_factor ** 2)
                globs_per_section[region][section]['region_area_right'] = \
                    np.where(region_cells[1] >= center_x)[0].shape[
                        0] * (
                            scale_factor ** 2)
                densities = section_density_map[region_cells].flatten()
                densities = (densities[densities != 0], len(densities))
                globs_per_section[region][section]['density3d'] = densities

        return globs_per_section
def get_brain_bbox_and_image(bboxes, directory, experiment_id, section, image_needed, scale=4):
    thumb = cv2.imread(f"{directory}/thumbnail-{experiment_id}-{section}.jpg", cv2.IMREAD_GRAYSCALE)
    _, brain_bbox, _ = detect_brain(thumb)
    thumb = cv2.resize(thumb, (0, 0), fx=64 // scale, fy=64 // scale)
    if image_needed:
        for bbox in bboxes[section]:
            x, y, w, h = bbox.scale(64)
            image = cv2.imread(f'{directory}/full-{experiment_id}-{section}-{x}_{y}_{w}_{h}.jpg',
                               cv2.IMREAD_GRAYSCALE)
            x, y, w, h = bbox.scale(64 // scale)
            thumb[y: y + h, x: x + w] = cv2.resize(image, (0, 0), fx=1.0 / scale, fy=1.0 / scale)
    return thumb, brain_bbox.pad(5, 5).scale(64)
    def __init__(self, experiment_id, section, data, base_time, input_dir,
                 structure_tree):
        self.structure_tree = structure_tree
        self.experiment_id = experiment_id
        self.data = data
        # self.hist_button = widgets.Button(description=f"Show detailed histograms")
        # self.hist_button.layout.width = 'auto'
        # self.hist_button.on_click(self.clicked)
        self.output = widgets.Output()
        self.section = section
        display(Markdown('---'))
        if self.section != 'totals':
            self.section = int(section)
            display(
                widgets.Label(
                    f"Experiment {self.experiment_id}, section {self.section}")
            )
            self.annotated_button_bar = self.AnnotationsButtonBar(
                self.experiment_id, self.data, self.section, base_time,
                input_dir, self.output)
            display(self.output)
            display(widgets.HBox((self.annotated_button_bar, )))
            if os.path.isfile(
                    f'{input_dir}/{experiment_id}/thumbnail-{self.experiment_id}-{section}.jpg'
            ):
                thumb = Image.open(
                    f'{input_dir}/{experiment_id}/thumbnail-{self.experiment_id}-{section}.jpg'
                )
                _, rect, _ = detect_brain(
                    np.array(thumb.convert('LA'))[:, :, 0])
                thumb = thumb.crop((
                    *(rect.corners()[0]),
                    *(rect.corners()[1]),
                ))
            else:
                thumb = None
        else:
            display(widgets.Label(f"Experiment {self.experiment_id}, totals"))
            display(self.output)
            display(
                widgets.HBox(
                    (self.HeatmapAndPatchButtons(experiment_id, base_time,
                                                 input_dir), )))
            thumb = None

        with self.output:
            # plot_section_violin_diagram(self.data, structure_tree, thumb)
            plt.imshow(thumb)
            plt.axis('off')
            plt.show()
 def get_brain_metrics(self, section):
     thumbnail_file_name = os.path.join(self.directory, f'thumbnail-{self.id}-{section}.jpg')
     thumbnail = cv2.imread(thumbnail_file_name, cv2.IMREAD_GRAYSCALE)
     brain_mask, bbox, ctrs = detect_brain(thumbnail)
     brain_area = sum([Polygon(ctr.squeeze()).area for ctr in ctrs])
     return brain_area, bbox