使用 PIL TiffTags 从 .tif 图像元数据中提取比例尺
Extracting scale bar from .tif image metadata using PIL TiffTags
我是 Python 的新手,我希望从电子显微镜 (.tif) 图像中提取比例信息。
当我在记事本中打开文件并滚动到底部时,我看到一个标题“[Scan]”和它下面的一个项目 "PixelWidth=3.10059e-010"。
我想在 Python 中读取此值并将其用作测量图像内物理距离的校准因子。
我发现了一种使用 PIL () 的有前途的方法,但是在 运行 推荐代码时遇到错误。
from PIL import Image
from PIL.TiffTags import TAGS
with Image.open(imagetoanalyze) as img:
meta_dict = {TAGS[key] : img.tag[key] for key in img.tag.iterkeys()}
我希望这会创建一个 object "meta_dict",其中包含 "PixelWidth" 之类的字符串和“3.10059e-010”之类的浮点数。
相反,我看到了:
Traceback (most recent call last):
File "<ipython-input-62-4ea0187b2b49>", line 2, in <module>
meta_dict = {TAGS[key] : img.tag[key] for key in img.tag.iterkeys()}
File "<ipython-input-62-4ea0187b2b49>", line 2, in <dictcomp>
meta_dict = {TAGS[key] : img.tag[key] for key in img.tag.iterkeys()}
KeyError: 34682
显然我做错了什么。任何帮助将不胜感激。谢谢!
使用PIL,我认为使用for循环来设置你的字典,然后打印想要的结果会更清楚。
from PIL import Image
from PIL.TiffTags import TAGS
with Image.open(imagetoanalyze) as img:
meta_dict = {}
for key in img.tag: # don't really need iterkeys in this context
meta_dict[TAGS.get(key,'missing')] = img.tag[key]
# Now you can print your desired unit:
print meta_dict["PixelWidth"]
如果您只需要一个值,您也可以通过以下方式查找 PixelWidth
标签的编号:
for k in img.tag:
print k,TAGS.get(k,'missing')
然后只打印 img.tag[<thatnumber>]
而不填充字典。
看起来您的文件可能是 FEI SEM TIFF,其中包含 TIFF 标签 34682 中类似 INI 的元数据。
尝试使用 tifffile:
import tifffile
with tifffile.TiffFile('FEI_SEM.tif') as tif:
print(tif.fei_metadata['Scan']['PixelWidth'])
我是 Python 的新手,我希望从电子显微镜 (.tif) 图像中提取比例信息。
当我在记事本中打开文件并滚动到底部时,我看到一个标题“[Scan]”和它下面的一个项目 "PixelWidth=3.10059e-010"。
我想在 Python 中读取此值并将其用作测量图像内物理距离的校准因子。
我发现了一种使用 PIL (
from PIL import Image
from PIL.TiffTags import TAGS
with Image.open(imagetoanalyze) as img:
meta_dict = {TAGS[key] : img.tag[key] for key in img.tag.iterkeys()}
我希望这会创建一个 object "meta_dict",其中包含 "PixelWidth" 之类的字符串和“3.10059e-010”之类的浮点数。
相反,我看到了:
Traceback (most recent call last):
File "<ipython-input-62-4ea0187b2b49>", line 2, in <module>
meta_dict = {TAGS[key] : img.tag[key] for key in img.tag.iterkeys()}
File "<ipython-input-62-4ea0187b2b49>", line 2, in <dictcomp>
meta_dict = {TAGS[key] : img.tag[key] for key in img.tag.iterkeys()}
KeyError: 34682
显然我做错了什么。任何帮助将不胜感激。谢谢!
使用PIL,我认为使用for循环来设置你的字典,然后打印想要的结果会更清楚。
from PIL import Image
from PIL.TiffTags import TAGS
with Image.open(imagetoanalyze) as img:
meta_dict = {}
for key in img.tag: # don't really need iterkeys in this context
meta_dict[TAGS.get(key,'missing')] = img.tag[key]
# Now you can print your desired unit:
print meta_dict["PixelWidth"]
如果您只需要一个值,您也可以通过以下方式查找 PixelWidth
标签的编号:
for k in img.tag:
print k,TAGS.get(k,'missing')
然后只打印 img.tag[<thatnumber>]
而不填充字典。
看起来您的文件可能是 FEI SEM TIFF,其中包含 TIFF 标签 34682 中类似 INI 的元数据。
尝试使用 tifffile:
import tifffile
with tifffile.TiffFile('FEI_SEM.tif') as tif:
print(tif.fei_metadata['Scan']['PixelWidth'])