Skip to content

Commit

Permalink
Merge pull request #111 from DeepMicroscopy/storage
Browse files Browse the repository at this point in the history
A couple of small fixes (unfortunatly checked into the storage branch, where they did not belong).
  • Loading branch information
maubreville authored May 29, 2024
2 parents ec50242 + dca9a91 commit 17f74ec
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 70 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,29 @@

/* Get area of a polygon/surface */
function polygon_area(vector) {
let total = 0;

let len = Object.keys(vector).length/2
for (let i = 1; i <= len; i++) {

const addX = vector["x" + i];
const addY = vector["y" + (i === len ? 1 : i + 1)];
const subX = vector["x" + (i === len ? 1 : i + 1)];
const subY = vector["y" + i];
total += (addX * addY * 0.5) - (subX * subY * 0.5);
}
return Math.abs(total);
}

function rect_area(vector)
{
return Math.round((vector["x2"]-vector["x1"])*(vector["y2"]-vector["y1"]))
}

function line_length(vector) {
return Math.round(Math.sqrt(Math.pow(vector["x2"]-vector["x1"],2)+Math.pow(vector["y2"]-vector["y1"],2)))
}

/// Bind Annotation Properties to UI
class ShowAnnotationProperties{
constructor(viewer, exact_sync) {
Expand Down Expand Up @@ -27,7 +52,25 @@ class ShowAnnotationProperties{

$("#annotationLastEditor").text(annotation.last_editor.username);
$("#annotationLastEditor").attr("href", include_server_subdir(`/users/user/${annotation.last_editor.id}/`));


if (annotation.annotation_type.vector_type==3) // line
{
$("#annotationSizeLengthLabel").html('Length (px)');
$("#annotationSize").text(line_length(annotation.vector));
}
else
{
$("#annotationSizeLengthLabel").html('Area (px^2)');
if (annotation.annotation_type.vector_type==1) // rect
{
$("#annotationSize").text(rect_area(annotation.vector));

}
else
{
$("#annotationSize").text(polygon_area(annotation.vector));
}
}
$("#annotationRemark").val(annotation.description);

if (annotation.verified_by_user !== undefined)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,13 @@ <h5 id="active_image_name">{{ selected_image.name }}</h5>
</td>
</tr>

<tr>
<td> <label id="annotationSizeLengthLabel">Size/Length:</label></td>
<td>
<a id="annotationSize"></a>
</td>
</tr>

<tr>
<td>Unique ID:</td>
<td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class Migration(migrations.Migration):
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('frame_type', models.IntegerField(choices=[(0, 'z Stack'), (1, 'time series'), (255, 'undefined')], default=0)),
('descreption', models.CharField()),
('descreption', models.CharField(default='')),
('frame_id', models.IntegerField(default=0)),
('Image', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='FrameDescriptions', to='images.image')),
],
Expand Down
70 changes: 2 additions & 68 deletions exact/exact/images/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ class FrameDescription(models.Model):
)

frame_type = models.IntegerField(choices=FRAME_TYPES, default=FrameType.ZSTACK)
description = models.CharField()
file_path = models.CharField(default='')
description = models.CharField(max_length=160)
file_path = models.CharField(default='', max_length=320)
frame_id = models.IntegerField(default=0)
Image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='FrameDescriptions')

Expand Down Expand Up @@ -271,72 +271,6 @@ def save_file(self, path:Path):
converter.convert(str(path), 0)
self.objectivePower = 40
self.filename = path.name
# check if possible multi frame tiff
elif (len(Path(path).suffixes)>1) and (Path(path).suffixes[-2].lower().endswith('ome') and Path(path).suffixes[-1].lower().startswith('.tif')):

reader = AICSImage(str(path))
im = reader.get_stack().squeeze()
shape = im.shape # shape of 1st frame in series

image_saved = False
if (len(shape) == 4 and shape[-1] in [1, 3, 4]) or len(shape) == 3 and shape[-1] not in [1, 3, 4]:
image_saved = True
frames = shape[0]
self.frames = frames
z_positions=[str(x) for x in np.arange(frames)]
z_positions_num=[x for x in np.arange(frames)]

if reader.ome_metadata is None:
logger.warning('OME TIFF without metadata: '+str(path))
elif len(reader.ome_metadata.images)==0:
logger.warning('Number of images is zero'+str(path))
else:
z_positions=[]
z_positions_num=[]
for im_meta in reader.ome_metadata.images:
z_positions.append('%.2f %s' % (im_meta.pixels.planes[0].position_z,im_meta.pixels.planes[0].position_z_unit.value))
z_positions_num.append(im_meta.pixels.planes[0].position_z)

folder_path = Path(self.image_set.root_path()) / path.stem
os.makedirs(str(folder_path), exist_ok =True)
os.chmod(str(folder_path), 0o777)

self.save() # initially save

for frame_id in range(shape[0]):
vi = pyvips.Image.new_from_array(im[frame_id])
vi = vi.scaleimage()
height, width, channels = vi.height, vi.width, vi.bands
self.channels = channels

target_file = folder_path / "{}_{}_{}".format(1, frame_id + 1, path.name) #z-axis frame image
vi.tiffsave(str(target_file), tile=True, compression='lzw', bigtiff=True, pyramid=True, tile_width=256, tile_height=256)

# save FrameDescription object for each frame
FrameDescription.objects.create(
Image=self,
frame_id=frame_id,
file_path=target_file,
description=z_positions[frame_id],
frame_type=FrameDescription.FrameType.ZSTACK,
)

# z is the default position
if (0 in z_positions_num):
self.defaultFrame=z_positions_num.index(0)

# save first frame or default position for thumbnail etc.
if (frame_id == 0) or (z_positions_num[frame_id]==0):
self.filename = target_file.name

else:
path = Path(path).with_suffix('.tiff')
if old_path == path:
path = Path(path).with_suffix('.tif')

vi = pyvips.Image.new_from_file(str(old_path))
vi.tiffsave(str(path), tile=True, compression='lzw', bigtiff=True, pyramid=True, tile_width=256, tile_height=256)
self.filename = path.name

elif path.suffix.lower().endswith(".tiff") or path.suffix.lower().endswith(".tif"):
im = tifffile.imread(str(path))
Expand Down
4 changes: 4 additions & 0 deletions exact/util/slide_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ class OpenSlideWrapper(openslide.OpenSlide):
Wraps an openslide.OpenSlide object. The rationale here is that OpenSlide.read_region does not support z Stacks / frames as arguments, hence we have to encapsulate it
"""
@property
def nFrames(self):
return 1

def read_region(self, location, level, size, frame=0):
return openslide.OpenSlide.read_region(self, location, level, size)

Expand Down

0 comments on commit 17f74ec

Please sign in to comment.