如何在Python中对图像应用DCT?
我想在Python中对一张图片进行离散余弦变换(还有它的反变换),但我不知道最好的方法是什么,也不知道该怎么做。我查过PIL和OpenCV这两个库,但还是不太明白怎么使用它们。
2 个回答
14
这里有一个使用 scipy.fftpack
的例子:
from scipy.fftpack import dct, idct
# implement 2D DCT
def dct2(a):
return dct(dct(a.T, norm='ortho').T, norm='ortho')
# implement 2D IDCT
def idct2(a):
return idct(idct(a.T, norm='ortho').T, norm='ortho')
from skimage.io import imread
from skimage.color import rgb2gray
import numpy as np
import matplotlib.pylab as plt
# read lena RGB image and convert to grayscale
im = rgb2gray(imread('images/lena.jpg'))
imF = dct2(im)
im1 = idct2(imF)
# check if the reconstructed image is nearly equal to the original image
np.allclose(im, im1)
# True
# plot original and reconstructed images with matplotlib.pylab
plt.gray()
plt.subplot(121), plt.imshow(im), plt.axis('off'), plt.title('original image', size=20)
plt.subplot(122), plt.imshow(im1), plt.axis('off'), plt.title('reconstructed image (DCT+IDCT)', size=20)
plt.show()
另外,如果你把 2D DCT
系数数组 imF 的一小部分(在 log
领域)画出来,你会得到一个像下面这样的图(有棋盘格的图案):
12
来自 OpenCV 的内容:
DCT(src, dst, flags) → None Performs a forward or inverse Discrete Cosine transform of a 1D or 2D floating-point array. Parameters: src (CvArr) – Source array, real 1D or 2D array dst (CvArr) – Destination array of the same size and same type as the source flags (int) – Transformation flags, a combination of the following values CV_DXT_FORWARD do a forward 1D or 2D transform. CV_DXT_INVERSE do an inverse 1D or 2D transform. CV_DXT_ROWS do a forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.
DCT(离散余弦变换)在 scipy.fftpack 中也可以找到。