如何在Python中将DCT应用于图像?

时间:2011-08-18 16:33:41

标签: python image-processing opencv python-imaging-library dct

我想在Python中对一个图像应用离散余弦变换(以及反向),我想知道最好的方法是什么以及如何做。我看过PIL和OpenCV,但我仍然不明白如何使用它。

2 个答案:

答案 0 :(得分:8)

来自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.

Here is an example of it being used

DCT也可在scipy.fftpack中使用。

答案 1 :(得分:5)

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域中绘制log系数数组imF的一小片,则会得到如下图所示(带有棋盘图案):

enter image description here