【问题标题】:What is the best way to convert a monochrome image to a binary string?将单色图像转换为二进制字符串的最佳方法是什么?
【发布时间】:2021-06-28 01:33:29
【问题描述】:

目前我的计划是使用numpy.ndarray.tolist(numpy.asarray(img)) 并遍历每三个元素(因为每个像素都表示为三个 RGB 整数),检查它是否为零以生成二进制字符串。我确信一定有更好的方法来做到这一点,我只是不确定是什么......

【问题讨论】:

    标签: python python-3.x image encryption binary


    【解决方案1】:

    Numpy 和 Pillow 是非常要好的朋友。您只需将图像作为参数提供即可将枕头图像转换为 numpy 数组:

     from PIL import Image 
     import numpy as np
    
     path = "path\to\image.jpg"
     image_file = Image.open(path) 
     bilevel_img = image_file.convert('1')
     data_array = np.array(bilevel_img)
     print(data_array)
    

    注意,“1”模式是双层的,所以你会得到一个 True / False 数组。

    使用灰度模式可能会好很多,然后在您定义的阈值处进行双电平:

     gray = np.array(img.convert("L"))
     print(gray)
     threshold = 128 # cutoff between 0 and 255
     bilevel_array = (gray > threshold).astype(int)
     print(bilevel_array)
    

    这给了你一个二进制数组!

    【讨论】:

    • 感谢您的帮助,虽然我确实需要不同的解决方案,但我仍然从您的回复中学到了一些东西!
    猜你喜欢
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多