1

I want to get a simple python list from the pixel colors from an image the output list should be monodimensional ordered as:

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

to get the image data:

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)]

is there a way to get:

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] 
2
  • f = f[0], does this work? Commented Jan 10, 2014 at 16:02
  • maybe: list(f) or f =f.tolist() Commented Jan 10, 2014 at 16:04

2 Answers 2

1

since opencv images in cv2 are numpy arrays, use 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])
Sign up to request clarification or add additional context in comments.

Comments

-1

.tolist() method kindly adviced by Mr 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'>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.