-3

I've installed the libraries such as numPy, sciPy. Is openCV necessary for this? using Scikit-image will solve the purpose? Division of image into blocks (eg. a 256x256 px image into 4x4 px blocks then conversion into matrices) can be done using Matlab, but I want to ensure if it can be done using python.

Aashi
  • 21
  • 2
  • 8

1 Answers1

3

Python's (and numpy's) slicing and indexing makes this simple to do. You don't need OpenCV or scikit-image for this (but you do need something to read the images, of course).

>>> import numpy as np
>>> image = np.random.rand(256,256) # random grayscale float image
>>> blocks = np.array([image[i:i+4, j:j+4] for j in range(0,256,4) for i in range(0,256,4)])
>>> blocks.shape
(4096, 4, 4)

>>> image = np.random.rand(256,256,3) # random 3-ch float image
>>> blocks = np.array([image[i:i+4, j:j+4] for j in range(0,256,4) for i in range(0,256,4)])
>>> blocks.shape
(4096, 4, 4, 3)
alkasm
  • 22,094
  • 5
  • 78
  • 94
  • Thanks for your help, but the code is not working. – Aashi Jun 22 '17 at 11:40
  • Can you be more specific? You should be sure you have `import numpy as np` first. I'll edit that into the post. Let me know what problems you're having. – alkasm Jun 22 '17 at 12:19
  • what if I wanted to divide any nXn colored image into m number of blocks? – Aashi Jun 23 '17 at 19:49
  • Well you can calculate the block size by `n/m`. Of course you'll have to figure out what you want to do if you have an image that isn't exactly divided into your block size...you could append them to the last blocks to make them bigger, or have smaller blocks at the end, or ignore them, or whatever you want to do. Obviously it depends on what you want to do with them. – alkasm Jun 23 '17 at 21:41
  • http://answers.opencv.org/question/53694/divide-an-image-into-lower-regions/ worked for me, thanks anyways! – Aashi Jun 29 '17 at 20:55