You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过OpenCV从小波离散小波变换(DWT)中获取一维矩阵?

How to Extract a 1D Matrix from Haar Wavelet Transform for Images

Hey there! Let's walk through your issue step by step, plus fix that small code bug first.

First: Fix the Variable Name Typo

You've got a typo in your code: cA2 = coeff should be cA2 = coeffs (or target a specific component of coeffs). That line would throw a NameError otherwise since coeff isn't defined.

Why Aren't You Getting a 1D Matrix?

The reason you're getting 2D outputs is because you're feeding a 2D image matrix into wavedec. When performing wavelet transforms on 2D data (like images), the function returns a list of 2D coefficient arrays:

  • The first element is the approximate coefficient (cA2 for level=2 decomposition)
  • The following elements are the detail coefficients (cD2, cD1 for level=2)

Each of these matches the 2D structure of your input image. To get a 1D matrix, you need to flatten these 2D arrays.

Solution 1: Flatten a Single Coefficient Component

If you only need the approximate coefficient (or one specific detail coefficient) as a 1D array, use flatten() or ravel():

import cv2
import numpy as np
from pwt import wavedec

# Assuming 'resize' is your input image
imgcv1 = cv2.split(resize)[0]
cv2.boxFilter(imgcv1, 0, (7,7), imgcv1, (-1,-1), False, cv2.BORDER_DEFAULT)
imf = np.float32(imgcv1)/255.0 

coeffs = wavedec(imf, "haar", level = 2)
# Flatten the approximate coefficient (cA2) to 1D
cA2_1d = coeffs[0].flatten()
print(cA2_1d)
  • flatten() creates a new 1D array, while ravel() returns a view of the original array (memory-efficient if you don't need to modify the data).

Solution 2: Combine All Coefficients into One 1D Array

If you want to merge all wavelet coefficients (approximate + all details) into a single 1D matrix, concatenate the flattened versions of each component:

# Concatenate all flattened coefficient arrays into one 1D array
all_coeffs_1d = np.concatenate([coeff.flatten() for coeff in coeffs])
print(all_coeffs_1d)

A quick note: The coeffs list from wavedec follows the order [cA_level, cD_level, cD_level-1, ..., cD_1], so make sure that order aligns with what you need for your use case.

内容的提问来源于stack exchange,提问作者Novadi Lintang

火山引擎 最新活动