【问题标题】:How to convert all bytes files under the folder into images如何将文件夹下的所有字节文件转换为图像
【发布时间】:2018-05-07 13:25:04
【问题描述】:
import numpy
from PIL import Image
import binascii

def getMatrixfrom_bin(filename,width):
    with open(filename, 'rb') as f:
        content = f.read()
    ...
    return fh

filename = "path\bin_filename(1)"
im = Image.fromarray(getMatrixfrom_bin(filename,512))
//getMatrixfrom_bin () is a function that generates a matrix from the binary bytes
im.save("path\bin_filename(1).png")

上面的代码一次只能生成一张图片,现在我需要把路径下的所有二进制文件都转换成图片,怎么办?

【问题讨论】:

    标签: python image python-2.7 numpy image-processing


    【解决方案1】:

    如果你在一个体面的(例如 Unix/Linux/macOS)平台上,你可以在不编写任何 Python 的情况下将所有二进制文件并行转换为 PNG 图像,如果你使用 GNU Parallel 和 ImageMagick,它们安装在大多数 Linux 发行版上,并可通过 homebrew 用于 macOS。

    因此,将所有以.bin 结尾的文件并行转换为PNG 图像的命令是:

    parallel 's=$(wc -c < {}); w=512; ((h=s/w)); convert -depth 8 -size ${w}x${h} gray:{} {.}.png' ::: *bin
    

    如果你不习惯的话有点吓人,所以我会分解它。基本上它正在为所有以.bin 结尾的文件并行运行“一些东西”,所以再看看它是:

    parallel 'some stuff' ::: *.bin
    

    什么是“一些东西”?好吧,请注意{} 是我们当前正在处理的文件的简写,所以它是这样做的:

    s=$(wc -c < {})         # s=total bytes in current file, i.e. s=filesize
    w=512                   # w=image width
    ((h=s/w))               # h=s/w, i.e. h=height in pixels of current file
    convert ...
    

    最后一行,以convert 开头的那个正在调用 ImageMagick 告诉它您的图像深度是 8 位,像素尺寸是 WxH,然后它将当前文件读入图像并将其保存为以PNG 结尾的新图像,而不是原始扩展名。简单!


    当然,如果你知道宽度是 500 像素,高度是 400 像素,生活会更轻松:

    parallel 'convert -depth 8 -size 500x400 gray:{} {.}.png' ::: *bin
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 2020-06-09
      • 2022-11-10
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多