如何使用skimage(Python)实际保存图像

bat*_*ike 4 python opencv image image-processing matplotlib

我目前正在应用Zhang-Suen细化算法来研究我想要稍后跟踪的一些细丝.这需要我输出灰度图像以便使用OpenCV识别对象.

import matplotlib
import matplotlib.pyplot as plt
import skimage.io as io
"load image data"
Img_Original =  io.imread( './data/test1.bmp')      # Gray image, rgb images   need pre-conversion

"Convert gray images to binary images using Otsu's method"
from skimage.filter import threshold_otsu
Otsu_Threshold = threshold_otsu(Img_Original)   
BW_Original = Img_Original < Otsu_Threshold    # must set object region as 1, background region as 0 !

#...
"Apply the algorithm on images"
BW_Skeleton = zhangSuen(BW_Original)
# BW_Skeleton = BW_Original
"Display the results"
fig, ax = plt.subplots(1, 2)
ax1, ax2 = ax.ravel()
ax1.imshow(BW_Original, cmap=plt.cm.gray)
ax1.set_title('Original binary image')
ax1.axis('off')
ax2.imshow(BW_Skeleton, cmap=plt.cm.gray)
ax2.set_title('Skeleton of the image')
ax2.axis('off')
plt.show()
Run Code Online (Sandbox Code Playgroud)

使用matplotlib绘制的图像正是我想要的(黑色和白色).当我使用skimage或cv2将输出图像写入文件路径时,我得到一个蓝色和红色的类似图像.我唯一的问题是我无法将此蓝/红色图像转换为灰度图像!所以从本质上讲,我的输出图像是无用的.如果这是一个微不足道的问题,请原谅我,但是有没有将图像写入文件路径的协议?当我使用这些工具时,我应该注意图像类型(即字节,颜色/灰度,格式)?提前致谢!

Mol*_*lly 7

您可以设置已保存数据的颜色映射,以便在OpenCV中打开图像时,它将是灰度级的.

以下是一些示例数据示例:

data = np.random.rand(256,256)
Run Code Online (Sandbox Code Playgroud)

您可以直接保存数据:

plt.imsave('test.png', data, cmap = plt.cm.gray)
Run Code Online (Sandbox Code Playgroud)

或保存整个数字:

plt.savefig('test2.png')
Run Code Online (Sandbox Code Playgroud)