
- SciPy - Home
- SciPy - Introduction
- SciPy - Environment Setup
- SciPy - Basic Functionality
- SciPy - Relationship with NumPy
- SciPy Clusters
- SciPy - Clusters
- SciPy - Hierarchical Clustering
- SciPy - K-means Clustering
- SciPy - Distance Metrics
- SciPy Constants
- SciPy - Constants
- SciPy - Mathematical Constants
- SciPy - Physical Constants
- SciPy - Unit Conversion
- SciPy - Astronomical Constants
- SciPy - Fourier Transforms
- SciPy - FFTpack
- SciPy - Discrete Fourier Transform (DFT)
- SciPy - Fast Fourier Transform (FFT)
- SciPy Integration Equations
- SciPy - Integrate Module
- SciPy - Single Integration
- SciPy - Double Integration
- SciPy - Triple Integration
- SciPy - Multiple Integration
- SciPy Differential Equations
- SciPy - Differential Equations
- SciPy - Integration of Stochastic Differential Equations
- SciPy - Integration of Ordinary Differential Equations
- SciPy - Discontinuous Functions
- SciPy - Oscillatory Functions
- SciPy - Partial Differential Equations
- SciPy Interpolation
- SciPy - Interpolate
- SciPy - Linear 1-D Interpolation
- SciPy - Polynomial 1-D Interpolation
- SciPy - Spline 1-D Interpolation
- SciPy - Grid Data Multi-Dimensional Interpolation
- SciPy - RBF Multi-Dimensional Interpolation
- SciPy - Polynomial & Spline Interpolation
- SciPy Curve Fitting
- SciPy - Curve Fitting
- SciPy - Linear Curve Fitting
- SciPy - Non-Linear Curve Fitting
- SciPy - Input & Output
- SciPy - Input & Output
- SciPy - Reading & Writing Files
- SciPy - Working with Different File Formats
- SciPy - Efficient Data Storage with HDF5
- SciPy - Data Serialization
- SciPy Linear Algebra
- SciPy - Linalg
- SciPy - Matrix Creation & Basic Operations
- SciPy - Matrix LU Decomposition
- SciPy - Matrix QU Decomposition
- SciPy - Singular Value Decomposition
- SciPy - Cholesky Decomposition
- SciPy - Solving Linear Systems
- SciPy - Eigenvalues & Eigenvectors
- SciPy Image Processing
- SciPy - Ndimage
- SciPy - Reading & Writing Images
- SciPy - Image Transformation
- SciPy - Filtering & Edge Detection
- SciPy - Top Hat Filters
- SciPy - Morphological Filters
- SciPy - Low Pass Filters
- SciPy - High Pass Filters
- SciPy - Bilateral Filter
- SciPy - Median Filter
- SciPy - Non - Linear Filters in Image Processing
- SciPy - High Boost Filter
- SciPy - Laplacian Filter
- SciPy - Morphological Operations
- SciPy - Image Segmentation
- SciPy - Thresholding in Image Segmentation
- SciPy - Region-Based Segmentation
- SciPy - Connected Component Labeling
- SciPy Optimize
- SciPy - Optimize
- SciPy - Special Matrices & Functions
- SciPy - Unconstrained Optimization
- SciPy - Constrained Optimization
- SciPy - Matrix Norms
- SciPy - Sparse Matrix
- SciPy - Frobenius Norm
- SciPy - Spectral Norm
- SciPy Condition Numbers
- SciPy - Condition Numbers
- SciPy - Linear Least Squares
- SciPy - Non-Linear Least Squares
- SciPy - Finding Roots of Scalar Functions
- SciPy - Finding Roots of Multivariate Functions
- SciPy - Signal Processing
- SciPy - Signal Filtering & Smoothing
- SciPy - Short-Time Fourier Transform
- SciPy - Wavelet Transform
- SciPy - Continuous Wavelet Transform
- SciPy - Discrete Wavelet Transform
- SciPy - Wavelet Packet Transform
- SciPy - Multi-Resolution Analysis
- SciPy - Stationary Wavelet Transform
- SciPy - Statistical Functions
- SciPy - Stats
- SciPy - Descriptive Statistics
- SciPy - Continuous Probability Distributions
- SciPy - Discrete Probability Distributions
- SciPy - Statistical Tests & Inference
- SciPy - Generating Random Samples
- SciPy - Kaplan-Meier Estimator Survival Analysis
- SciPy - Cox Proportional Hazards Model Survival Analysis
- SciPy Spatial Data
- SciPy - Spatial
- SciPy - Special Functions
- SciPy - Special Package
- SciPy Advanced Topics
- SciPy - CSGraph
- SciPy - ODR
- SciPy Useful Resources
- SciPy - Reference
- SciPy - Quick Guide
- SciPy - Cheatsheet
- SciPy - Useful Resources
- SciPy - Discussion
SciPy - fft - dct() Function
The scipy.fft.dct() function returns the Discrete Cosine Transform (DCT) of an input array. DCT uses cosine functions to transfer data from the spatial (time or pixel) domain to the frequency domain. This transformation is critical for evaluating, compressing, or simplifying data.
DCT often finds its applications in signal compression such as audio coding and applications of image compression, for example JPEG. It isolates the most important aspects by focusing on significant information at lower frequencies, which helps in effectively compressing the data representation.
Errors may occur if the input array is of unsupported data types and with complex numbers. Secondly, wrong optional parameter values; for example, it might be an unsupported type or a wrong index of the axis, can give rise to an error. The errors are corrected by proper formatting and acceptable values of parameters.
The scipy.fft.dct() method accepts optional arguments including type (to allow choice of a DCT variant), n (truncate or pad data), axis for multidimensional transforms, and norm for normalization. Parameters like these allow for special settings in applications such as compression or signal processing. It also works well along with idct (Inverse DCT) to build up data and other tools available in SciPy for advanced frequency analyses and data manipulation.
SciPy supports four versions of DCT: Type I for boundary conditions, Type II is quite popular in compression, for example, JPEG, Type III is the inverse of Type II under scaling, and Type IV is fully orthogonal for symmetric data.
Syntax
The syntax for the SciPy dct() method is as follows −
.dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False)
Parameters
This method accepts the following parameters −
x − Input array to be transformed.
type − Type of the DCT (1, 2, 3, or 4; default is 2).
n − Length of the transform (truncates or pads x as needed).
axis − Axis along which the DCT is applied (default: last axis).
norm − Normalization mode ('ortho' for orthonormal transform).
overwrite_x − If True, allows modification of x to save memory.
Return Value
y (ndarray of real) − The DCT-transformed array.
Example 1: Basic DCT Transformation of a 1D Array
This is an example of applying the DCT to a simple one-dimensional array. The method transforms the data into a frequency domain representation that exhibits both obvious and subtle changes.
The following array, [1, 2, 3, 4], is passed through the scipy dct() function. The result is the display of frequency coefficients representing the original data in terms of cosine functions.
import numpy as np from scipy.fft import dct data = [1, 2, 3, 4] result = dct(data) print("DCT of data:", result)
When we run above program, it produces following result
DCT of data: [20. -6.30864406 0. -0.44834153]
Example 2: Normalized DCT Using norm='ortho'
Using norm='ortho' calculates the orthonormal DCT with frequency coefficients scaled to produce uniform energy distribution. This reduces the complexity of comparison and interpretation of the changed values.
This is an example of performing the dct() method on the array [1, 2, 3, 4] with the norm='ortho' option for normalization. The result is a representation of the input array in the frequency domain with equally scaled coefficients.
import numpy as np from scipy.fft import dct data = [1, 2, 3, 4] result = dct(data, norm='ortho') print("Normalized DCT of data:", result)
Following is an output of the above code
Normalized DCT of data: [ 5. -2.2304425 0. -0.15851267]
Example 3: DCT Applied to 2D Arrays with Axis Parameter
In DCT, multidimensional data can be processed by using the axis parameter. The transformation is applied to the rows of a 2D array and turns spatial data into frequency components for each row.
The following code applies the dct() function to each row of a 2D array with the use of the parameter axis=-1. In the final result, you will have the converted 2D array, which now contains frequency coefficients for every row, thus being suitable for image or grid data analysis.
import numpy as np from scipy.fft import dct data = np.array([[1, 2, 3], [4, 5, 6]]) result = dct(data, axis=-1) print("DCT of 2D data along rows:\n", result)
Output of the above code is as follows
DCT of 2D data along rows: [[ 1.20000000e+01 -3.46410162e+00 -4.44089210e-16] [ 3.00000000e+01 -3.46410162e+00 -4.44089210e-16]]
Example 4: Padding Input Data with n Parameter in DCT
The parameter 'n' determines the size of the DCT. This allows you to pad or truncate the input data, thus altering the frequency resolution or harmonizing arrays of different sizes.
In the below code, we use n=6, the input array is padded to a predefined length. The Discrete Cosine Transform is then computed from the padded array yielding frequency coefficients that include the effect of additional data points without adding new information.
import numpy as np from scipy.fft import dct data = [1, 2, 3] result = dct(data, n=6) print("DCT with padded data:", result)
Output of the above code is as follows
DCT with padded data: [ 1.20000000e+01 6.31319305e+00 -3.46410162e+00 -5.65685425e+00 -4.44089210e-16 3.48476592e+00]
Example 5: Handling Unsupported Data Types in DCT
When input data are given in an unsupported format like strings or complex integers, the DCT may yield wrong output due to its internal calculations which require only real numbers for computation, being integers or floats.
In the below example we created a input list contains strings that are incompatible with dct(). Executing the code throws an error with a ValueError message. The solution is ensuring that the input data is a numeric list, such as integers or floats.
from scipy.fft import dct import numpy as np # Correct input: array of numbers data = np.array([1, 2, 3], dtype=float) # Ensures it's a NumPy array with float values result = dct(data) print("Correct DCT of data:", result) # Incorrect input: array of strings data = ["a", "b", "c"] # Invalid input try: result = dct(np.array(data, dtype=float)) # Attempt to convert to NumPy array with float type print("DCT of data:", result) except ValueError as e: # ValueError occurs when trying to convert strings to float print("Error:", e) # Expected error due to invalid input type
Output of the above code is as follows −
Corrected DCT of data: [ 1.20000000e+01 -3.46410162e+00 -4.44089210e-16] ValueError: could not convert string to float: 'a'