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

jmn*_*ong 9 python opencv image-processing dct python-imaging-library

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

San*_*Dey 9

示例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()
Run Code Online (Sandbox Code Playgroud)

此外,如果您绘制2D DCT系数数组 imF 的一小部分(log域中),您将得到如下图(带有棋盘图案):

在此处输入图片说明


agf*_*agf 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.

这是一个使用它的例子.

DCT也可以在scipy.fftpack找到.