繁体   English   中英

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

[英]How to change the colors of a binary image using python?

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

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

好吧,一般来说,假设您有一个 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”到 255 的 8 位最大值

你可以用调色板来做,但在这里我制作了一个完整的 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')

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM