0

他们是否有任何方法可以使用 python 将二进制图像的颜色更改为除黑色和白色之外的其他两种不同颜色。如果输入二进制图像是“unit8”数据类型并且相同的输入图像是“bool”数据类型,如何实现这一点?

d = gdal.Open(....)
band = d.GetRasterBand(1)
arr1 = band.ReadAsArray()
thresh = threshold_otsu(arr1)
binary = arr1 > thresh
plt.imshow(binary)
4

2 回答 2

0

好吧,一般来说,假设您有一个 x,y 图像,因此是 bool 类型的数组;您需要像使用 numpy 一样生成 (x,y,3) 数组:

colImage = np.zeros((x,y,3), dtype="uint8")

3 的维度用 rgb 编码颜色,所以

colImage[:,:,0] = boolImage * 255 # for red
colImage[:,:,1] = boolimage * 255 # for green
colImage[:,:,2] = boolimage * 255 # for blue

如果我没记错的话。* 255 是从布尔值“1”到最大 8 位的 255

于 2019-06-26T07:19:23.513 回答
0

你可以用调色板来做,但在这里我制作了一个完整的 RGB 版本。

from PIL import Image
from skimage import data
from skimage.filters import threshold_otsu

# Load image
image = data.camera()

# Threshold image to binary
thresh = threshold_otsu(image)
binary = image > thresh

# Make 3 channel RGB image same dimensions
RGB = np.zeros((binary.shape[0],binary.shape[1],3), dtype=np.uint8)

# Make True pixels red
RGB[binary]  = [255,0,0]
# Make False pixels blue
RGB[~binary] = [0,0,255]

# Display result
Image.fromarray(RGB).show()

在此处输入图像描述


您可以像这样稍微不同地表达同一件事:

from skimage import data
from skimage.filters import threshold_otsu

# Load image
image = data.camera()

# Threshold image to binary
thresh = threshold_otsu(image)
binary = image > thresh

# Define red and blue
red  = np.array([255,0,0],dtype=np.uint8)
blue = np.array([0,0,255],dtype=np.uint8)

# Make RGB array, pre-filled with blue
RGB = np.zeros((binary.shape[0],binary.shape[1],3), dtype=np.uint8) + blue

# Overwrite with red where threshold exceeded, i.e. where mask is True
RGB[binary] = red

但是,仅存储 2 种颜色的完整 RGB 图像相当浪费空间,因为每个像素有 3 个字节(R、G 和 B)。最好制作一个调色板图像,其中每个像素只存储 1 个字节,并将该字节用作可以容纳 256 种颜色的调色板的索引。你可以这样做:

from PIL import Image
from skimage import data
from skimage.filters import threshold_otsu

# Load image
image = data.camera()

# Threshold image to binary
thresh = threshold_otsu(image)
binary = image > thresh

# Make a palette with 2 entries, magenta and yellow
palette = [  
    255, 0, 255,  # magenta
    255, 255, 0   # yellow
]

# Zero-pad the palette to 256 RGB colours, i.e. 768 values
palette += (768-len(palette))*[0]

# Make PIL/Pillow image from the binary array
p = Image.fromarray((binary*1).astype(np.uint8))

# Push the palette into image and save
p.putpalette(palette)
p.save('result.png')

在此处输入图像描述

于 2019-06-26T07:55:32.360 回答