以下是一个不使用OpenCV的阈值分割的示例代码:
import numpy as np
from PIL import Image
def threshold_segmentation(image_path, threshold):
# 打开图像文件
img = Image.open(image_path)
# 将图像转换为灰度图
img = img.convert("L")
# 将图像转换为NumPy数组
img_array = np.array(img)
# 创建一个与图像大小相同的全零数组
segmented_img = np.zeros_like(img_array)
# 对每个像素进行阈值分割
for i in range(img_array.shape[0]):
for j in range(img_array.shape[1]):
if img_array[i, j] >= threshold:
segmented_img[i, j] = 255
# 将NumPy数组转换回图像
segmented_img = Image.fromarray(segmented_img)
# 显示图像
segmented_img.show()
# 测试代码
threshold_segmentation("image.jpg", 128)
请注意,此代码使用了PIL库(Python Imaging Library)来处理图像。它打开图像文件,并将其转换为灰度图像。然后,它使用NumPy数组进行阈值分割操作,根据阈值将像素值设置为0(黑色)或255(白色)。最后,它将NumPy数组转换回图像,并显示结果图像。
请确保在运行此代码之前安装了PIL库(可以使用pip install pillow
命令进行安装)。还要将image.jpg
替换为您要进行阈值分割的图像文件的路径,并将threshold
替换为您希望使用的阈值。