OpenCV图片编解码实战:DCT变换与Numpy对数函数解析

小岛来信
小岛来信
发布时间:2026-10-14| 3人浏览过
原创

本文通过OpenCV与Numpy实现图片的离散余弦变换(DCT)编解码实践。详细解析了如何提取不同尺寸的DCT系数以控制图像重建质量,并深入探讨了Numpy中log函数默认以自然常数e为底数的特性及其在图像处理中的应用。

OpenCV图片编解码实战:DCT变换与Numpy对数函数解析

原始图像如下所示:

查看图像属性可知,该图片尺寸为816×2100像素:

DCT系数提取与图像重建效果

对应的Python实现代码如下:


import cv2
import numpy as np
import matplotlib.pyplot as plt
 
img = cv2.imread('11.jpg', 0)
img1 = img.astype('float')
img_dct = cv2.dct(img1)
img_dct_log = np.log(abs(img_dct))
img_recor = cv2.idct(img_dct)
recor_temp = img_dct[0:100,0:100]
recor_temp2 = np.zeros(img.shape)
recor_temp2[0:100,0:100] = recor_temp
print recor_temp.shape
print recor_temp2.shape
img_recor1 = cv2.idct(recor_temp2)
plt.subplot(221)
plt.imshow(img)
plt.title('original')
plt.subplot(222)
plt.imshow(img_dct_log)
plt.title('dct transformed')
plt.subplot(223)
plt.imshow(img_recor)
plt.title('idct transformed')
plt.subplot(224)
plt.imshow(img_recor1)
plt.title('idct transformed2')
 
plt.show()

仅保留100×100的DCT系数进行重构,效果如下:

若使用800×1000的DCT系数进行重构:

此时图像细节有所恢复,质量略有提升:


import cv2
import numpy as np
import matplotlib.pyplot as plt
 
img = cv2.imread('11.jpg', 0)
img1 = img.astype('float')
img_dct = cv2.dct(img1)
img_dct_log = np.log(abs(img_dct))
img_recor = cv2.idct(img_dct)
recor_temp = img_dct[0:800,0:1000]
recor_temp2 = np.zeros(img.shape)
recor_temp2[0:800,0:1000] = recor_temp
print recor_temp.shape
print recor_temp2.shape
img_recor1 = cv2.idct(recor_temp2)
plt.subplot(221)
plt.imshow(img)
plt.title('original')
plt.subplot(222)
plt.imshow(img_dct_log)
plt.title('dct transformed')
plt.subplot(223)
plt.imshow(img_recor)
plt.title('idct transformed')
plt.subplot(224)
plt.imshow(img_recor1)
plt.title('idct transformed2')
 
plt.show()

当使用816×1200的DCT系数进行重构时:

可以看出图像质量已恢复至接近原始水平。

代码逻辑与Numpy.log函数底数分析

对代码逻辑进行分析:

变量img_dct存储的是DCT变换后的矩阵,而img_d_log则是先对矩阵元素取绝对值,再计算对数得到的矩阵。

具体代码为:img_dct_log = np.log(abs(img_dct))

这里涉及一个关键问题:对数的底数是多少?

通过打印输出img_dct_log与abs(img_dct)进行对比验证:

打印结果如下:

其中9.45971865e+04表示科学计数法,即9.45971865 × 10^4,换算后为94597.1865。

通过对比可知,只有当底数取自然常数e时,计算结果才符合题目输出的对数值,因此Python中Numpy的log函数默认以自然常数e为底数。

至此,关于利用OpenCV实现图片编解码的实践介绍完毕,更多相关OpenCV图片编解码内容可参考本站往期文章或继续浏览后续章节,感谢支持!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。