如何使用python更改二进制图像的颜色?

时间:2019-06-26 06:00:54

标签: python image-processing raster binary-image

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

import gdal
from skimage.filters import threshold_otsu
import matplotlib.pyplot as plt

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

2 个答案:

答案 0 :(得分:0)

好吧,通常来说,假设您有一个x,y图像,因此是布尔型数组;您需要像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”到255的8位最大值

答案 1 :(得分: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()

enter image description here


您可以这样表达同一件事:

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')

enter image description here