在python3下对数据分块(8x8大小)使用OpenCV的离散余弦变换DCT
在MATLAB中有blkproc (blockproc)对数据处理, 在python下没找到对应的Function,
这里利用numpy 的split(hsplit和vsplit) 对数据分块处理成8x8的小块, 然后在利用OpenCV的dct函数做变换, 同时利用idct 验证数据变换是否正确.
import numpy as np
import cv2
a = np.arange(256).reshape((16,16))
print("ori data: \n{}".format(a))
m,n = a.shape
print(m,n)
# Y = np.zeros(256).reshape((16,16))
hdata = np.vsplit(a,n/8) # 垂直分成高度度为8 的块
for i in range(0, n//8):
blockdata = np.hsplit(hdata[i],m/8)
#垂直分成高度为8的块后,在水平切成长度是8的块, 也就是8x8 的块
for j in range(0, m//8):
block = blockdata[j]
print("block[{},{}] data \n{}".format(i,j,blockdata[j]))
Yb = cv2.dct(block.astype(np.float))
print("dct data\n{}".format(Yb))
iblock = cv2.idct(Yb)
print("idct data\n{}".format(iblock))
以下是最后个8x8块的数据:
block[1,1] data
[[136 137 138 139 140 141 142 143]
[152 153 154 155 156 157 158 159]
[168 169 170 171 172 173 174 175]
[184 185 186 187 188 189 190 191]
[200 201 202 203 204 205 206 207]
[216 217 218 219 220 221 222 223]
[232 233 234 235 236 237 238 239]
[248 249 250 251 252 253 254 255]]
dct data
[[ 1.56400000e+03 -1.82216412e+01 0.00000000e+00 -1.90481783e+00
0.00000000e+00 -5.68239222e-01 0.00000000e+00 -1.43407825e-01]
[-2.91546259e+02 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[-3.04770852e+01 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[-9.09182756e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[-2.29452520e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]]
idct data
[[136. 137. 138. 139. 140. 141. 142. 143.]
[152. 153. 154. 155. 156. 157. 158. 159.]
[168. 169. 170. 171. 172. 173. 174. 175.]
[184. 185. 186. 187. 188. 189. 190. 191.]
[200. 201. 202. 203. 204. 205. 206. 207.]
[216. 217. 218. 219. 220. 221. 222. 223.]
[232. 233. 234. 235. 236. 237. 238. 239.]
[248. 249. 250. 251. 252. 253. 254. 255.]]
数据与原数据值大小一致.