【问题标题】:python OpenCV output listpython OpenCV 输出列表
【发布时间】:2014-01-29 16:29:37
【问题描述】:

我想从图像的像素颜色中获取一个简单的 python 列表,输出列表应该是一维排序的:

output = [B1,G1,R1,B2,G2,R2,B3,G3,R3....] 

获取图片数据:

import cv2
image = cv2.imread('a.png')
image
array([[[  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255]],

       [[  0, 255,   0],
        [  0, 255,   0],
        [  0, 255,   0]],

       [[255,   0,   0],
        [255,   0,   0],
        [255,   0,   0]]], dtype=uint8)

f = image.flatten()
f
[array([  0,   0, 255,   0,   0, 255,   0,   0, 255,   0, 255, 0,   0,
       255,   0,   0, 255,   0, 255,   0,   0, 255,   0,   0, 255, 0, 

0], dtype=uint8)]

有没有办法获得:

f = [0,0,255,0,0,255,0,0,255,0,255,0,0,255,0,0,255,0,255,0,0,255,0,0,255,0,0] 

【问题讨论】:

  • f = f[0],这行得通吗?
  • 也许:list(f) 或 f =f.tolist()

标签: python list opencv converter nested-lists


【解决方案1】:

由于 cv2 中的 opencv 图像是 numpy 数组,所以使用 numpy:

import cv2
import numpy as np

# simulate a bgr image:
>>> a = np.array([[[1,2,3], [4,5,6]],[[1,2,3], [4,5,6]]])
>>> a
array([[[1, 2, 3],
        [4, 5, 6]],

       [[1, 2, 3],
        [4, 5, 6]]])
>>> b = np.reshape(a,-1)
>>> b
array([1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6])

【讨论】:

    【解决方案2】:

    .tolist() 方法由 Abid Rahman 先生友情建议

    >>> import numpy as np
    >>> f = np.random.randint(0,255,(3,3,3))
    >>> print(f)
    [[[193  61  68]
      [223 102   0]
      [ 45 204   7]]
    
     [[ 64 193  60]
      [ 94 157  49]
      [ 38 116   5]]
    
     [[ 64 107 197]
      [225 246  22]
      [186 102 156]]]
    >>> g = f.flatten()
    >>> print g
    [193  61  68 223 102   0  45 204   7  64 193  60  94 157  49  38 116   5
      64 107 197 225 246  22 186 102 156]
    
    >>> g.dtype
    dtype('int32')
    >>> type(g)
    <type 'numpy.ndarray'>
    
    >>> h = g.tolist()
    >>> print h
    [193, 61, 68, 223, 102, 0, 45, 204, 7, 64, 193, 60, 94, 157, 49, 38,
    116, 5, 64, 107, 197, 225, 246, 22, 186, 102, 156]
    >>> type(h)
    <type 'list'>
    

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多