如何将Sauvola阈值得到的布尔型numpy数组转换为Pillow图像
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

