forked from camicroscope/SlideLoader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBioFormatsReader.py
191 lines (167 loc) · 7.27 KB
/
BioFormatsReader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import ImageReader
import bfbridge
import threading
import dev_utils
import ome_types
from file_extensions import BIOFORMATS_EXTENSIONS
#from bfbridge.old_global_thread_manager import check_out_thread_local_object, save_thread_local_object, thread_to_object_dict_lock
jvm = bfbridge.BFBridgeVM()
# Try to keep BioFormats thread alive as long as possible
bfthread_holder = threading.local()
# todo deleteme
import threading
class X:
def __init__(self, s):
self.x = s
def __del__(self):
print("dying thread " + self.x, flush=True)
loo = threading.local()
class BioFormatsReader(ImageReader.ImageReader):
@staticmethod
def reader_name():
return "bioformats"
@staticmethod
def extensions_set():
return BIOFORMATS_EXTENSIONS
# Pick the reader
def __init__(self, imagepath):
#self.__class__.l = threading.local()
#self.__class__.l.a = X()
global loo
if not hasattr(loo, 'a'):
loo.a = X("now")
if not hasattr(dev_utils.ll, "u"):
dev_utils.ll.u = X("later?")
print("__init__ called", flush=True)
print("TrID instance:", flush=True)
print(threading.get_native_id(), flush=True)
# bfthread = get_thread_local_object()
# if bfthread is None:
# # the following throws:
# bfthread = bfbridge.BFBridgeThread()
# save_thread_local_object(bfthread)
#from threading import get_ident
#import os
#thread_id = os.getpid() #get_ident()
# using getpid here caused having a new thread that wasn't attached
#bfthread = check_out_thread_local_object(thread_id)
# if bfthread is None:
# print("LOCK: none, now construct", flush=True)
# try:
# bfthread = bfbridge.BFBridgeThread(jvm)
# print("LOCK: constructed", flush=True)
# except Exception as f:
# failure = f
# print("LOCK: fail", flush=True)
# print(f)
# save_thread_local_object(thread_id, bfthread)
# print("LOCK: release")
# else:
# print("LOCK: using")
# thread_to_object_dict_lock.acquire()
global bfthread_holder
if not hasattr(bfthread_holder, "bfthread"):
bfthread_holder.bfthread = bfbridge.BFBridgeThread(jvm)
# Conventionally internal attributes start with underscore.
# When using them without underscore, there's the risk that
# a property has the same name as a/the getter, which breaks
# the abstract class. Hence all internal attributes start with underscore.
self._bfreader = bfbridge.BFBridgeInstance(bfthread_holder.bfthread)
if self._bfreader is None:
raise RuntimeError("cannot make bioformats instance")
print("__init__ called2", flush=True)
self._image_path = imagepath
code = self._bfreader.open(imagepath)
if code < 0:
raise IOError("Could not open file " + imagepath + ": " + self._bfreader.get_error_string())
print("__init__ called3", flush=True)
# Note: store actually the format in self._vendor ("Hamamatsu NDPI" instead of "Hamamatsu")
self._vendor = self._bfreader.get_format()
self._level_count = self._bfreader.get_resolution_count()
self._dimensions = (self._bfreader.get_size_x(), self._bfreader.get_size_y())
self._level_dimensions = [self._dimensions]
for l in range(1, self._level_count):
self._bfreader.set_current_resolution(l)
self._level_dimensions.append( \
(self._bfreader.get_size_x(), self._bfreader.get_size_y()))
print("dimensions:")
print(self._level_dimensions)
@property
def level_count(self):
return self._level_count
@property
def dimensions(self):
return self._dimensions
@property
def level_dimensions(self):
return self._level_dimensions
@property
def associated_images(self):
return None
def read_region(self, location, level, size):
self._bfreader.set_current_resolution(level)
return self._bfreader.open_bytes_pil_image(0, \
location[0], location[1], size[0], size[1])
def get_thumbnail(self, max_size):
print("Starting BioFormatsReader get_thumbnail", flush=True)
return self._bfreader.open_thumb_bytes_pil_image(0, max_size[0], max_size[1])
def get_basic_metadata(self, extended):
metadata = {}
if not hasattr(self, "_md5"):
self._md5 = dev_utils.file_md5(self._image_path)
try:
ome_xml_raw = self._bfreader.dump_ome_xml_metadata()
except BaseException as e:
raise OverflowError("XML metadata too large for file considering the preallocated buffer length. " + str(e))
print(ome_xml_raw, flush=True)
print("Starting metadata", flush=True)
print("raw_str:")
print(str(ome_xml_raw))
print(ome_xml_raw)
# TODO try except here IA
try:
ome_xml = ome_types.from_xml(ome_xml_raw)
print("continuing metadata", flush=True)
except BaseException as e:
raise RuntimeError("get_basic_metadata: OME-XML parsing of metadata failed, error: " + \
str(e) + " when parsing: " + ome_xml)
# https://www.openmicroscopy.org/Schemas/Documentation/Generated/OME-2016-06/ome_xsd.html
# https://bio-formats.readthedocs.io/en/latest/metadata-summary.html
print(ome_xml.images[0], flush=True)
# "comment" attribute of metadata
print(str(ome_xml.images[0]), flush=True)
print(str(ome_xml), flush=True)
print("size")
print(ome_xml.images[0].pixels.size_x, flush=True)
print(ome_xml.images[0].pixels.size_y, flush=True)
print(ome_xml.images[0].pixels.physical_size_x, flush=True)
print(ome_xml.images[0].pixels.physical_size_y, flush=True)
metadata['width'] = str(self._dimensions[0])
metadata['height'] = str(self._dimensions[1])
try:
metadata['mpp-x'] = str(ome_xml.images[0].pixels.physical_size_x)
metadata['mpp-y'] = str(ome_xml.images[0].pixels.physical_size_y)
except:
metadata['mpp-x'] = "0"
metadata['mpp-y'] = "0"
metadata['vendor'] = self._vendor
metadata['level_count'] = int(self._level_count)
# TODO IA: fix maginification
print("magnification:")
try:
metadata['objective'] = ome_xml.instruments[0].objectives[0].nominal_magnification
except:
try:
metadata['objective'] = ome_xml.instruments[0].objectives[0].calibrated_magnification
except:
metadata['objective'] = -1.0
# The following caused result to be shown incorrectly due to https://github.com/camicroscope/SlideLoader/issues/73
# Also, it's a too long string because BioFormats tries to show the complete metadata.
# metadata['comment'] = ome_xml_raw
metadata['comment'] = ""
metadata['study'] = ""
metadata['specimen'] = ""
metadata['md5sum'] = self._md5
if not hasattr(self, "_metadata"):
self._metadata = metadata
return metadata