【问题标题】:Problem on converting gray level image to binary image using Python使用Python将灰度图像转换为二值图像的问题
【发布时间】:2021-05-24 06:35:50
【问题描述】:

我对 Python 完全陌生。我拍了一张彩色照片。然后将其转换为灰度图像。到目前为止还不错。但是当我尝试将此灰度转换为二值图像时,我得到的是黄色和紫色的图像,而不是白色和黑色。

import matplotlib.pyplot as plt
import numpy as np

painting=plt.imread("ff.jpg")
print(painting.shape)
print("The image consists of %i pixels" % (painting.shape[0] * painting.shape[1]))
plt.imshow(painting);
#This displayed by color image perfectly

from skimage import data, io, color
painting_gray = color.rgb2gray(painting)
print(painting_gray)
io.imshow(painting_gray)
print("This is the Gray scale version of the original image")
#This displayed my gray scale image perfectly

#Now comes the code for binary image:
num = np.array(painting_gray)
print(num)
bin= num >0.5
bin.astype(np.int)
plt.imshow(bin)
#The display showed an image with yellow and purple color instead of white and black

我得到的图像图是:

The gray scale image:

The binary image that I got:

请帮我获取黑白二值图像。

【问题讨论】:

  • 这是因为 imshow 使用默认颜色图。试试 plt.imshow(bin, cmap='gray', vmin=0, vmax=255) 或 plt.gray()
  • 这非常有效。谢谢。
  • @Stefan 也许您应该提交此评论作为答案,以便 OP 可以接受它?
  • 好的,我可以这样做,但我认为类似的问题在其他地方已经有了答案。

标签: python numpy image-processing grayscale binary-image


【解决方案1】:

这是因为imshow 使用默认颜色图,称为 viridis。像素颜色是从此颜色图中选择的,使用从 min(img) 到 max(img) 的像素值的比例。

解决这个问题的方法不止一种:

imshow中指定颜色映射:

   plt.imshow(bin, cmap='gray', vmin=0, vmax=255)

选择颜色图:

   plt.gray() 

另一种选择色图的方法:

   plt.colormap('gray')

旁注:bin 是用于转换二进制数的函数,因此将其用作变量名可能会导致代码出现问题。

【讨论】:

    【解决方案2】:

    试试:

    
    from skimage.filters import threshold_otsu
    thresh = threshold_otsu(painting_gray)
    binary = painting_gray> thresh
    
    

    在这里阅读更多: https://scikit-image.org/docs/stable/auto_examples/applications/plot_thresholding.html https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_thresholding.html

    【讨论】:

    • 整个问题是他在 cmets 上使用了上面提到的默认颜色图。
    猜你喜欢
    • 2021-06-06
    • 2015-07-26
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2018-08-15
    相关资源
    最近更新 更多