我是Python新手,我希望从电子显微镜(.tif)图像中提取比例信息。
当我在记事本中打开文件并滚动到底部时,我会看到标题“扫描”和下面的"PixelWidth=3.10059e-010“。
我想用Python读取这个值,并使用它作为测量图像中物理距离的校准因子。
我发现了一种使用PIL (https://stackoverflow.com/a/46910779/10244370)的很有前途的方法,但是在运行推荐代码时遇到了一个错误。
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()}我预期这将创建一个对象"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很明显我做错了什么。任何帮助都将不胜感激。谢谢!
发布于 2019-02-05 16:46:12
看起来您的文件可能是file,它在TIFF标记34682中包含类似于INI的元数据。
尝试使用蒂夫文件
import tifffile
with tifffile.TiffFile('FEI_SEM.tif') as tif:
print(tif.fei_metadata['Scan']['PixelWidth'])发布于 2019-02-05 00:56:12
使用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>]而不填充字典。
https://stackoverflow.com/questions/54526139
复制相似问题