图像实际上是如何用 skimage 保存的 (Python)

How are images actually saved with skimage (Python)

我目前正在应用 Zhang-Suen thinning algorithm 来磨练一些我想稍后追踪的灯丝。这需要我输出灰度图像,以便使用 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()

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

您可以设置保存数据的颜色图,以便在OpenCV中打开图像时它是灰度图。

这里有一些示例数据作为示例:

data = np.random.rand(256,256)

您可以保存data directly

plt.imsave('test.png', data, cmap = plt.cm.gray)

或保存整个figure:

plt.savefig('test2.png')