保存tiff文件时出现奇怪的错误(堆栈灰度),知道吗?:
文件“ C:\ Users \ ptyimg_np.MT00200169 \ Anaconda3 \ lib \ site-packages \ tifffile \ tifffile.py”,第1241行,保存sampleformat = {'u':1,'i':2,'f':3,'c':6} [datadtype.kind] KeyError:'b'
我的代码是
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from skimage.morphology import watershed
from skimage.feature import peak_local_max
from scipy import ndimage
from skimage import img_as_float
from skimage import exposure,io
from skimage import external
from skimage.color import rgb2gray
from skimage.filters import threshold_local , threshold_niblack
import numpy as np
import tifffile
from joblib import Parallel, delayed
import sys
# Load an example image
input_namefile = sys.argv[1]
output_namefile = 'seg_'+ input_namefile
#Settings
block_size = 25 #Size block of the local thresholding
img = io.imread(input_namefile, plugin='tifffile')
thresh = threshold_niblack(img, window_size=block_size , k=0.8) #
res = img > thresh
res = np.asanyarray(res)
print("saving segmentation")
tifffile.imsave(output_namefile, res , photometric='minisblack' )
[该错误似乎是由在已安装的tifffile
版本中写入布尔图像的错误引起的。但是,该错误已在较新的版本中修复(我的当前环境中为2020.2.16)。在我的机器上,这可以正常工作:
import numpy as np
import tifffile
tifffile.imsave('test.tiff', np.random.random((10, 10)) > 0.5)
并且对于布尔型映像,永远不会执行导致版本崩溃的行。
所以,长话短说,请使用python -m pip install -U tifffile
升级您的tifffile版本,您的程序应该可以运行!
首先进行一些分析。令人反感的行:
sampleformat = {'u': 1, 'i': 2, 'f': 3, 'c': 6}[datadtype.kind]
正在导致KeyError
异常,因为datadtype.kind
(NumPy数据类型)的值设置为b
,并且该词典中没有[Cis]。它仅适合b
,i
,u
和f
类型(分别是有符号整数,无符号整数,浮点数和复数浮点数)。类型c
为布尔值。这看起来像是您正在使用的代码中的错误。如果它不被支持,那么代码应该真正捕获异常并以更加用户友好的方式对其进行报告,而不是仅转储异常以供您了解。
我的建议是将此问题作为作者的错误提出。
根本原因
(这是基于分析的推测,所以可能是错误的,我只是将其作为可能原因提供),对您的代码进行的检查显示:b
上面的第三行会将img = io.imread(input_namefile, plugin='tifffile') thresh = threshold_niblack(img, window_size=block_size , k=0.8) # res = img > thresh res = np.asanyarray(res) tifffile.imsave(output_namefile, res , photometric='minisblack' )
设置为布尔值或布尔数组,具体取决于res
和img
中每个像素的值(我对NumPy不够了解,无法对其进行推算)这个)。
但是,不管它们是一个还是多个
booleans
,因此,当您尝试使用thresh
调用编写它们时,它会抱怨所使用的类型(如上所述,它似乎无法满足要求正确地获取布尔值)。基于其他地方的示例代码:imsave()
我怀疑您应该使用与最后一行类似的内容将应用于图像,然后将结果值写入:
image = data.coins()
mask = image > 128
masked_image = image * mask
img = io.imread(input_namefile, plugin='tifffile')
thresh = threshold_niblack(img, window_size=block_size , k=0.8)
mask = image > 128 # <-- unsure if this is needed.
res = img * thresh # <-- add this line.
res = np.asanyarray(res)
tifffile.imsave(output_namefile, res , photometric='minisblack' )
行,因为在我看来阈值已经为您提供了遮罩。我
可能
在这一点上是错误的,所以我的建议仍然是向作者提出。