使用Python将灰度图像转换为二进制图像的问题

我对 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:

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

womenzhelihaiyouyu22 回答:使用Python将灰度图像转换为二进制图像的问题

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

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

imshow 中指定颜色映射:

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

选择色图:

   plt.gray() 

另一种选择颜色图的方法:

   plt.colormap('gray')

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

,

试试:


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

本文链接:https://www.f2er.com/372216.html

大家都在问