将图像数组切成子数组


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 块的代码.我正在尝试将此数组转换为 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] 被指定为"列表索引超出范围"时,将显示错误。

我猜你的数组,即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]])

替换这些行:

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

最新更新