You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Sauvola阈值得到的布尔型numpy数组转换为Pillow图像

Convert Boolean NumPy Array to Pillow Image

No worries, converting that boolean binary_sauvola array to a Pillow image is straightforward—you just need to adjust the data type and format first, since Pillow works best with standard 8-bit grayscale values (0-255) instead of boolean True/False.

Here's how to do it step by step, building on your existing code:

Step 1: Convert Boolean Array to 8-bit Grayscale

Boolean arrays in NumPy store True as 1 and False as 0. To get a proper black-and-white image, we'll scale these values to 0 (black) and 255 (white), then cast to uint8 (the standard 8-bit integer type for images):

# Scale boolean values to 0/255 and convert to uint8
binary_uint8 = (binary_sauvola * 255).astype(numpy.uint8)

If you want inverted colors (black foreground on white background), just flip the values:

# Invert: True becomes 0 (black), False becomes 255 (white)
binary_uint8_inverted = ((1 - binary_sauvola) * 255).astype(numpy.uint8)

Step 2: Create Pillow Image from the NumPy Array

Use Pillow's Image.fromarray() method to turn the formatted array into a PIL Image object:

from PIL import Image

# Create the Pillow image
pil_image = Image.fromarray(binary_uint8)

# Optional: Save or display the result
pil_image.save("sauvola_binary_result.png")  # PNG is better for binary images to avoid compression artifacts
pil_image.show()

Full Complete Code

Putting it all together with your original code:

from PIL import Image
import numpy as np
from skimage.color import rgb2gray
from skimage.filters import threshold_sauvola

# Load and process the image
im = Image.open("test.jpg")
pix = np.array(im)
img = rgb2gray(pix)

# Apply Sauvola thresholding
window_size = 25
thresh_sauvola = threshold_sauvola(img, window_size=window_size)
binary_sauvola = img > thresh_sauvola

# Convert to Pillow image
binary_uint8 = (binary_sauvola * 255).astype(np.uint8)
pil_image = Image.fromarray(binary_uint8)

# Save or display
pil_image.save("sauvola_binary.jpg")
pil_image.show()

A quick note: Using PNG instead of JPG for saving binary images is usually better because JPG uses lossy compression which can introduce artifacts in sharp black-white edges.

内容的提问来源于stack exchange,提问作者R.hagens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:19:54