【问题标题】:Using python opencv to load image from zip使用 python opencv 从 zip 加载图像
【发布时间】:2014-01-26 23:27:36
【问题描述】:

我能够成功地从 zip 加载图像:

with zipfile.ZipFile('test.zip', 'r') as zfile:
    data = zfile.read('test.jpg')
    # how to open this using imread or imdecode?

问题是:如何在不先保存图像的情况下使用 imread 或 imdecode 打开它以便在 opencv 中进行进一步处理?

更新:

这是我得到的预期错误。我需要将'data'转换成opencv可以使用的类型。

data = zfile.read('test.jpg')
buf = StringIO.StringIO(data)
im = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
# results in error: TypeError: buf is not a numpy array, neither a scalar

a = np.asarray(buf)
cv2.imdecode(a, cv2.IMREAD_GRAYSCALE)
# results in error: TypeError: buf data type = 17 is not supported

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    使用numpy.frombuffer()从字符串创建一个uint8数组:

    import zipfile
    import cv2
    import numpy as np
    
    with zipfile.ZipFile('test.zip', 'r') as zfile:
        data = zfile.read('test.jpg')
    
    img = cv2.imdecode(np.frombuffer(data, np.uint8), 1)    
    

    【讨论】:

      【解决方案2】:

      HYRY's answer 确实提供了最优雅的解决方案


      在 Python 中读取图像不太符合"There should be one-- and preferably only one --obvious way to do it."

      有时您可能宁愿避免在应用程序的某些部分使用numpy。并改用Pillowimread。如果有一天你发现自己处于这种情况,那么希望下面的代码 sn-p 会有一些用处:

      import zipfile
      
      with zipfile.ZipFile('test.zip', 'r') as zfile:
          data = zfile.read('test.jpg')
      
      # Pillow
      from PIL import Image
      from StringIO import StringIO
      import numpy as np
      filelike_buffer = StringIO(data)
      pil_image = Image.open(filelike_buffer)
      np_im_array_from_pil = np.asarray(pil_image)
      print type(np_im_array_from_pil), np_im_array_from_pil.shape
      # <type 'numpy.ndarray'> (348, 500, 3)
      
      # imread
      from imread import imread_from_blob
      np_im_array = imread_from_blob(data, "jpg")
      print type(np_im_array), np_im_array.shape
      # <type 'numpy.ndarray'> (348, 500, 3)
      

      "How to read raw png from an array in python opencv?" 的回答提供了类似的解决方案。

      【讨论】:

      猜你喜欢
      • 2016-08-10
      • 2018-03-19
      • 2021-08-06
      • 2013-04-13
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多