예제 #1
0
def copy_image(filename, new_filename):
    _, original_extension = os.path.splitext(filename)
    _, new_extension = os.path.splitext(new_filename)

    # Read image
    if original_extension.lower() == '.mhd':
        metaimage = MetaImage(filename=filename)
        if new_extension.lower() == '.mhd':
            metaimage.write(new_filename)
        elif new_extension.lower() == '.png':
            pil_image = metaimage.get_image()
            pil_image.save(new_filename)
        else:
            raise Exception('Unknown output image extension ' + new_extension)
    elif original_extension.lower() == '.png':
        if new_extension.lower() == '.mhd':
            pil_image = PIL.Image.open(filename)
            metaimage = MetaImage(data=np.asarray(pil_image))
            metaimage.write(new_filename)
        elif new_extension.lower() == '.png':
            copyfile(filename, new_filename)
        else:
            raise Exception('Unknown output image extension ' + new_extension)
    else:
        raise Exception('Unknown input image extension ' + original_extension)
예제 #2
0
def get_image_as_http_response(filename, post_processing_method=''):
    _, extension = os.path.splitext(filename)
    buffer = BytesIO()
    start = time.time()
    if extension.lower() == '.mhd':
        reader = MetaImage(filename=filename)
        source = reader
        # Convert raw data to image, and then to a http response
        pil_image = reader.get_image()
        spacing = reader.get_spacing()
        if spacing[0] != spacing[1]:
            # Compensate for anistropic pixel spacing
            real_aspect = pil_image.width * spacing[0] / (pil_image.height *
                                                          spacing[1])
            current_aspect = float(pil_image.width) / pil_image.height
            new_width = int(pil_image.width * (real_aspect / current_aspect))
            new_height = pil_image.height
            pil_image = pil_image.resize((new_width, new_height))
    elif extension.lower() == '.png':
        pil_image = PIL.Image.open(filename)
        source = pil_image
    else:
        raise Exception('Unknown output image extension ' + extension)

    if post_processing_method is not '':
        post_processing = post_processing_register.get(post_processing_method)
        new_image = post_processing.post_process(np.asarray(pil_image), source,
                                                 filename)
        if len(new_image.shape) > 2 and new_image.shape[2] == 3:
            pil_image = PIL.Image.fromarray(new_image, 'RGB')
        else:
            pil_image = PIL.Image.fromarray(new_image, 'L')

    #print('Image loading time', time.time() - start, 'seconds')
    pil_image.save(buffer, "PNG", compress_level=1
                   )  # TODO This function is very slow due to PNG compression
    #print('Image loading time with save to buffer', time.time() - start, 'seconds')

    return HttpResponse(buffer.getvalue(), content_type="image/png")
    def add_subjects_to_path(self, path, form):
        # Create label file
        label_file = open(join(path, 'labels.txt'), 'w')

        # Create a .txt file with the labels matching the sequence name
        sequence_label_file = open(join(path, 'sequence_to_label.txt'), 'w')

        # Find labels with parents
        labels = form.cleaned_data['labels']
        label_dict = {}
        has_parent_dict = {}
        label_file.write('All labels involved: \n\n')
        for label_id in labels:
            label = Label.objects.get(pk=label_id)
            label_name = get_complete_label_name(label)
            label_file.write(label_name + '\n')
            has_parent_dict[label_name] = False
            label_dict[label_name] = None

        for start_label in has_parent_dict:
            for full_label in has_parent_dict:
                if full_label.startswith(start_label) & (start_label !=
                                                         full_label):
                    has_parent_dict[full_label] = True

        # Assign children to the parent class
        label_file.write(
            '\nClassification based on the following parent labels: \n\n')
        counter = 0
        for label in has_parent_dict:
            if has_parent_dict[label] == False:
                label_file.write(label + '\n')
                for label_name in label_dict:
                    if label_name.startswith(label):
                        label_dict[label_name] = counter
                counter += 1
        nb_parent_classes = counter

        label_file.close()

        # For each subject
        subjects = Subject.objects.filter(dataset__task=self.task)
        for subject in subjects:
            # Get labeled images
            labeled_images = ImageAnnotation.objects.filter(
                task=self.task, rejected=False, image__subject=subject)
            if labeled_images.count() == 0:
                continue

            width = form.cleaned_data['width']
            height = form.cleaned_data['height']

            sequence_frames = []
            labels = []

            for labeled_image in labeled_images:
                label = ImageLabel.objects.get(
                    image__image_annotation=labeled_image)

                if get_complete_label_name(label.label) in label_dict.keys():
                    # Get sequence
                    key_frame = KeyFrameAnnotation.objects.get(
                        image_annotation=labeled_image)
                    image_sequence = labeled_image.image
                    nr_of_frames = image_sequence.nr_of_frames

                    start_frame = 0
                    end_frame = nr_of_frames
                    if form.cleaned_data[
                            'displayed_frames_only'] and not self.task.show_entire_sequence:
                        start_frame = max(
                            0, key_frame.frame_nr - self.task.frames_before)
                        end_frame = min(
                            nr_of_frames,
                            key_frame.frame_nr + self.task.frames_after + 1)

                    for i in range(start_frame, end_frame):
                        # Get image
                        filename = image_sequence.format.replace('#', str(i))
                        if filename[-4:] == '.mhd':
                            metaimage = MetaImage(filename=filename)
                            image = metaimage.get_image()
                        else:
                            image = PIL.Image.open(filename)

                        # Setup assigned colormode
                        if form.cleaned_data['colormode'] != image.mode:
                            image = image.convert(
                                form.cleaned_data['colormode'])

                        # Resize
                        image = image.resize((width, height),
                                             PIL.Image.BILINEAR)

                        # Convert to numpy array and normalize
                        image_array = np.array(image).astype(np.float32)
                        image_array /= 255

                        if len(image_array.shape) != 3:
                            image_array = image_array[..., None]

                        sequence_frames.append(image_array)
                        labels.append(label_dict[get_complete_label_name(
                            label.label)])

                    if form.cleaned_data['sequence_wise'] and len(
                            sequence_frames) > 0:
                        input = np.array(sequence_frames, dtype=np.float32)
                        output = np.array(labels, dtype=np.uint8)

                        sequence_label_file.write(
                            join(
                                subject.name,
                                os.path.basename(
                                    os.path.dirname(image_sequence.format))) +
                            '\t' + str(output[0]) + '\n')

                        if form.cleaned_data['image_dim_ordering'] == 'theano':
                            input = np.transpose(input, [0, 3, 1, 2])

                        if form.cleaned_data['categorical']:
                            output = to_categorical(
                                output, nb_classes=nb_parent_classes)

                        subj_path = join(path, subject.name)
                        create_folder(subj_path)
                        try:
                            os.stat(subj_path)
                        except:
                            return False, 'Failed to create directory at ' + subj_path

                        f = h5py.File(
                            join(
                                subj_path,
                                os.path.basename(
                                    os.path.dirname(image_sequence.format) +
                                    '.hd5')), 'w')
                        f.create_dataset("data",
                                         data=input,
                                         compression="gzip",
                                         compression_opts=4,
                                         dtype='float32')
                        f.create_dataset("label",
                                         data=output,
                                         compression="gzip",
                                         compression_opts=4,
                                         dtype='uint8')
                        f.close()

                        sequence_frames = []
                        labels = []

            if not form.cleaned_data['sequence_wise'] and len(
                    sequence_frames) > 0:
                input = np.array(sequence_frames, dtype=np.float32)
                output = np.array(labels, dtype=np.uint8)

                if form.cleaned_data['image_dim_ordering'] == 'theano':
                    input = np.transpose(input, [0, 3, 1, 2])

                if form.cleaned_data['categorical']:
                    output = to_categorical(output, nb_classes=len(label_dict))

                f = h5py.File(join(path, subject.name + '.hd5'), 'w')
                f.create_dataset("data",
                                 data=input,
                                 compression="gzip",
                                 compression_opts=4,
                                 dtype='float32')
                f.create_dataset("label",
                                 data=output,
                                 compression="gzip",
                                 compression_opts=4,
                                 dtype='uint8')
                f.close()
        sequence_label_file.close()