使用skimage保存重建二值图像时报错‘cannot write mode F as PNG’求助
解决skimage保存PNG时的“cannot write mode F as PNG”错误
问题场景
使用skimage进行图像预处理后,调用imsave保存PNG时出现错误:OSError: cannot write mode F as PNG。预处理代码如下:
def image_process(image): img = imread(image) rem_img = remove(img) rgb_img = rgba2rgb(rem_img) gray_img = rgb2gray(rgb_img) bin_img = gray_img < threshold_otsu(gray_img) smooth_img = gaussian(bin_img) seed_px = np.copy(smooth_img) seed_px[1:-1 , 1:-1]=smooth_img.max() mask = smooth_img filled_img = reconstruction(seed_px , mask , method ='erosion') return filled_img
保存代码:
leaf_img = "neem.jpg" processed_img = image_process(leaf_img) imsave("BW/leaf.png", processed_img)
问题原因
错误中的mode F指**单精度浮点型(float32)**图像数据,而PNG格式不支持直接存储这种数据类型。你的预处理流程中,reconstruction函数返回的图像是浮点型数组,imsave底层依赖的PIL库无法将该类型直接编码为PNG。
解决方案
需要将浮点型图像数据转换为PNG支持的格式,常用的两种方法:
方法1:修改保存代码,转换为8位无符号整数(uint8)
将图像数据归一化到0-255范围后转换类型:
leaf_img = "neem.jpg" processed_img = image_process(leaf_img) # 归一化并转换为uint8格式 uint8_img = (processed_img * 255).astype(np.uint8) imsave("BW/leaf.png", uint8_img)
方法2:在预处理函数末尾直接转换格式
直接在image_process函数中返回可保存的格式,后续无需额外处理:
def image_process(image): img = imread(image) rem_img = remove(img) rgb_img = rgba2rgb(rem_img) gray_img = rgb2gray(rgb_img) bin_img = gray_img < threshold_otsu(gray_img) smooth_img = gaussian(bin_img) seed_px = np.copy(smooth_img) seed_px[1:-1 , 1:-1]=smooth_img.max() mask = smooth_img filled_img = reconstruction(seed_px , mask , method ='erosion') # 转换为PNG支持的uint8格式 return (filled_img * 255).astype(np.uint8)
调用保存代码:
leaf_img = "neem.jpg" processed_img = image_process(leaf_img) imsave("BW/leaf.png", processed_img)
补充说明
如果处理后的图像是二值类型(仅包含0和1),也可以直接转换:
uint8_img = filled_img.astype(np.uint8) * 255
内容的提问来源于stack exchange,提问作者Reyad Hassan
相关产品推荐
相关产品推荐

