Streem Streem - 22 days ago 15
Python Question

Divide image into blocks

I am using code to list image pixels with important information for later use - Red, Green, Blue, X, Y.

import numpy as np
from scipy.misc import imread

im = imread("image.jpg")

indices = np.dstack(np.indices((im.shape[:2])))
data = np.concatenate((im, indices), axis=-1)
print data


printed data:

R G B X Y
[[[237 233 234 0 0]
[235 231 232 0 1]
[243 234 237 0 2]
...,
[236 232 233 0 507]
[233 229 230 0 508]
[236 232 233 0 509]]


But it prints whole image data plain not in blocks. How to get this data in 2x2 blocks, 4 pixels information in block? Like this:

R G B X Y
[[[237 233 234 0 0]
[235 231 232 0 1]
[243 234 237 0 2]
[243 234 257 0 3]]

Answer

add the following to your code:

a = data[::2, ::2, :]
b = data[::2, 1::2, :]
c = data[1::2, ::2, :]
d = data[1::2, 1::2, :]
e = np.stack([a, b, c, d], axis=3)
print(e)

Using my image:

     R    G    B     X    Y
[[[  47  124  206    0    0]
  [  52  124  206    0    1]
  [  53  126  205    0    2]
  ..., 
  [  74  129  211    0 1021]
  [  73  130  211    0 1022]
  [  69  132  211    0 1023]]

 [[  47  124  206    1    0]
  [  51  123  205    1    1]
  [  53  126  205    1    2]
  ..., 
  [  75  130  212    1 1021]
  [  73  130  211    1 1022]
  [  69  130  210    1 1023]] ...

turns to:

[[[[  47   52   47   51]   R
   [ 124  124  124  123]   G
   [ 206  206  206  205]   B
   [   0    0    1    1]   X
   [   0    1    0    1]]  Y

  [[  53   58   53   58]   R
   [ 126  125  126  125]   G
   [ 205  204  205  204]   B
   [   0    0    1    1]   X
   [   2    3    2    3]]  Y

  [[  64   71   64   70]   R
   [ 127  126  127  127]   G
   [ 206  208  206  208]   B
   [   0    0    1    1]   X
   [   4    5    4    5]]  Y

  ..., 
Comments