【问题标题】:How can I recognize "PNG (Portable Network Graphics)" files in numpy.ndarray?如何识别 numpy.ndarray 中的“PNG(便携式网络图形)”文件?
【发布时间】:2019-08-30 08:56:46
【问题描述】:

我需要在numpy.ndarray 中找到png 文件。甚至有可能吗?

list_of_files 包含扩展名为 ['jpg', 'jpeg', 'bmp', 'tif', 'tiff', 'png'] 的文件。

for f in list_of_files:
    stream = open(f, 'rb')
    bytes = bytearray(stream.read())
    numpy_array = numpy.asarray(bytes, dtype=numpy.uint8)
image = cv2.imdecode(numpy_array, cv2.IMREAD_UNCHANGED)

【问题讨论】:

  • 您应该对字符串本身进行解码,而不是对 numpy 数组进行解码。你是什​​么意思“数组中的png文件”?
  • 您是否有理由不打开带有 png 扩展名的文件?您是否也在尝试查找没有扩展名或错误扩展名的 png 文件?

标签: python numpy opencv


【解决方案1】:

既然您只想处理 png 文件,那么只加载这些文件怎么样?您可以为此使用glob 库:

import glob

my_path = "<path_to_folder>"
for f in glob.glob(my_path + "/*.png"):
    #Do whatever here

基本上,glob.glob(my_path + "/*.png") 会为您提供路径中具有所需扩展名的文件的列表。

【讨论】:

    【解决方案2】:

    您可以在读取图像之前识别.png 文件:

    images={'png':[],'others':[]}
    for f in list_of_files:
        if f.split('.')[1:] == 'png':
            with open(f, 'rb') as stream:
                bytes = bytearray(stream.read())
            img_array = numpy.asarray(bytes, dtype=numpy.uint8)
            images['png'].append(cv2.imdecode(img_array, cv2.IMREAD_UNCHANGED))
        else:
            # w/e you want to do with the other images
    

    【讨论】:

      【解决方案3】:

      你可以使用imghdr.what

      import imghdr
      
      for f in list_of_files: 
           if (imghdr.what(f) == "png"): 
                print(f + " is a PNG file")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-21
        • 1970-01-01
        • 2015-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多