以下是对数据集中10张图像进行二值化的示例代码:

import cv2
import numpy as np

# 读取10张图像
images = []
for i in range(10):
    img = cv2.imread(f'image_{i}.jpg', cv2.IMREAD_GRAYSCALE)
    images.append(img)

# 计算每张图像的阈值
thresholds = []
for img in images:
    # 使用大津算法计算阈值
    _, th = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    thresholds.append(th)

# 将每张图像二值化
bin_images = []
for i in range(10):
    # 大于阈值的像素设为1,小于阈值的像素设为0
    bin_img = np.where(images[i] > thresholds[i], 1, 0)
    bin_images.append(bin_img)

# 显示二值化结果
for i in range(10):
    cv2.imshow(f'binary image {i}', bin_images[i]*255)
cv2.waitKey(0)
cv2.destroyAllWindows()

在上述代码中,我们首先使用cv2.imread函数读取10张图像,然后使用大津算法计算每张图像的阈值。接着,我们使用np.where函数将每张图像二值化,并将二值化结果存储在bin_images列表中。最后,我们使用cv2.imshow函数显示二值化结果。

需要注意的是,对于二值化结果,我们将大于阈值的像素设为1,小于阈值的像素设为0,并将像素值乘以255以便将其转换为8位图像


原文地址: https://www.cveoy.top/t/topic/eCTv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录