将图像数组切成子数组

时间:2014-12-16 09:01:37

标签: python arrays numpy

import numpy as np
import numpy as numpy
import cv2
from PIL import Image
from numpy import array
img = cv2.imread('image test.jpg')
gray = cv2.cvtColor(img.cv2.COLOR_BGR2GRAY)
myArray = array(gray)
slice = myArray[:8,:8]
print slice
print myArray 
k = cv2.waitKey(0)
if k == 27:
    cv2.destroyAllWindows()

这是我将图像数组切割成8 * 8 Block.i的代码。我试图将这个数组转换为8 * 8矩阵但是在运行上面的python代码时它产生了一个3 * 8矩阵。任何有关此信息都将有所帮助。

import numpy as np
import cv2
img = cv2.imread('image test.jpg')
gray = cv2.cvtColor(img.cv2.COLOR_BGR2GRAY)
data = np.asarray(gray)
data = np.split(data, data.shape[0]/8)
res = []
for arr in data:
    res.extend(np.split(arr,arr.shape[1]/8, axis = 1)
    print res[0]
k = cv2.waitKey(0)
if k == 27:
    cv2.destroyAllWindows() 



[[6 6 6 6 5 5 6 6]
 [7 7 7 6 6 6 7 7]
 [8 7 7 7 7 8 8 8]
 [8 7 6 6 7 8 8 8]
 [7 6 5 6 6 7 7 7]
 [6 5 5 5 6 6 7 7]
 [6 5 5 5 6 6 7 8]
 [6 6 6 6 6 7 8 9]]

此输出重复三次。当显示错误时,打印res [40]被赋予“list index out of range”。

2 个答案:

答案 0 :(得分:0)

我想你的阵列即myArray的形状 3 * n,n> = 8 。这是此行为的唯一可能原因。

演示:

>>> import numpy as np
>>> a = np.ones((16,16))
>>> slice = a[:8,:8]
>>> slice.shape
(8, 8)
>>> a = np.ones((3,16))
>>> slice = a[:8,:8]
>>> slice.shape
(3, 8)

将数据拆分为8x8子阵列的代码:

>>> import numpy as np
>>> data = np.random.randint(0,10,size=(320,240)) # create a random array of 320x240
>>> data = np.split(data, data.shape[0]/8)  # first split into 8x240, 8x240,... sub-arrays, i.e., split by rows of 8 first.
>>> res = []
>>> for arr in data:
...     res.extend(np.split(arr,arr.shape[1]/8, axis=1)) # now for each 8x240 sub-array split it column-wise into 8x8, 8x8,... arrays
... 
>>> res[0]
array([[5, 7, 3, 0, 2, 7, 5, 2],
       [8, 1, 8, 6, 3, 8, 8, 5],
       [7, 4, 6, 7, 9, 5, 1, 6],
       [0, 2, 4, 3, 1, 2, 0, 3],
       [4, 4, 8, 8, 5, 7, 4, 2],
       [2, 0, 8, 2, 9, 8, 9, 3],
       [6, 4, 0, 3, 3, 3, 5, 8],
       [6, 2, 8, 5, 0, 5, 1, 3]])
       .
       .
       .
>>> res[1199]
array([[8, 5, 5, 9, 1, 7, 5, 4],
       [0, 1, 8, 0, 3, 8, 5, 9],
       [2, 5, 3, 6, 7, 2, 8, 8],
       [1, 1, 7, 0, 0, 4, 3, 1],
       [5, 5, 8, 6, 6, 6, 5, 7],
       [9, 4, 2, 2, 7, 2, 1, 1],
       [6, 9, 5, 2, 5, 9, 3, 4],
       [1, 8, 1, 9, 7, 6, 7, 0]])

答案 1 :(得分:0)

替换这些行:

for arr in data:
    res.extend(np.split(arr,arr.shape[1]/8, axis = 1)
    print res[0]

使用:

for arr in data:
    res.extend(np.split(arr,arr.shape[1]/8, axis = 1)

for i in res: print i