首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将灰度图像转换为二进制图像并存储在python中的numpy数组中

将灰度图像转换为二进制图像并存储在python中的numpy数组中
EN

Stack Overflow用户
提问于 2022-11-09 12:51:51
回答 2查看 46关注 0票数 0

我正在研究一个使用Tensorflow Keras的二值图像分割问题。面具是灰度的,图像是RGB的。我需要将灰度掩码转换为二进制文件,并将它们存储在Numpy数组中。以下是守则:

代码语言:javascript
运行
复制
 from tensorflow.keras.preprocessing.image import load_img,ImageDataGenerator
    from skimage.transform import resize
    import os
    from tqdm import tqdm
    im_height,im_width = 256,256
    threshold = 150
    ids_test = next(os.walk("data/test/image"))[2] # list of names all images in the given path
    print("No. of images = ", len(ids_test))
    
    X_ts = np.zeros((len(ids_test), im_height, im_width, 3), dtype=np.float32)
    Y_ts = np.zeros((len(ids_test), im_height, im_width, 1), dtype=np.float32)
    for n, id_ in tqdm(enumerate(ids_test), total=len(ids_test)):
        img = load_img("data/test/image/"+id_, 
                        color_mode = "rgb")
        x_img = img_to_array(img)
        x_img = resize(x_img, (im_height, im_width,3), 
                        mode = 'constant', preserve_range = True)
        # Load masks
        mask = img_to_array(load_img("data/test/label/"+id_, 
                                      color_mode = "grayscale")) #grayscale   
        binarized = 1.0 * (mask > threshold)            
    
        mask = resize(binarized, (im_height,im_width,1), 
                      mode = 'constant', preserve_range = True)
        # Save images
        X_ts[n] = x_img/255.0
        Y_ts[n] = mask
EN

回答 2

Stack Overflow用户

发布于 2022-11-09 14:27:18

找到了解决我问题的方法。在经验评估之后,我设定了一个全局阈值,然后对图像进行阈值化。对发布的代码进行编辑。

票数 0
EN

Stack Overflow用户

发布于 2022-11-09 14:29:46

您可以在numpy (熊猫.)中使用比较操作很容易地将数字数组转换为布尔数组。

代码语言:javascript
运行
复制
array = np.random.random(5)
binary_array = array < 0.5
print(array)
print(binary_array)

这导致:

代码语言:javascript
运行
复制
[0.57145399 0.20060058 0.13103848 0.89899815 0.45459504]
[False  True  True False  True]

您可以轻松地检查数组的numpy类型:

代码语言:javascript
运行
复制
print(binary_array.dtype)
bool

如果阈值为th,则array > th将使用布尔dtype将数组的所有值转换为true If > th和false if <= th

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74375192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档