Image wavelet histogram

博客提到小波可用于图像纹理信息的快速索引,认为这是一个很好的研究方向。作者接下来要了解小波直方图的模式和计算算法,并打算做实验,为此需广泛阅读相关论文。

Wavelet can be used for fast indexing the texture information of the image. Very cool. It will be a good direction of study.

The following I should understand:

1.The pattern of wavelet histogram

2.The algorithm of computing the wavelet histogram

Do some experiment!

So first, I should read paper widely.

C语言-光伏MPPT算法:电导增量法扰动观察法+自动全局搜索Plecs最大功率跟踪算法仿真内容概要:本文档主要介绍了一种基于C语言实现的光伏最大功率点跟踪(MPPT)算法,结合电导增量法与扰动观察法,并引入自动全局搜索策略,利用Plecs仿真工具对算法进行建模与仿真验证。文档重点阐述了两种经典MPPT算法的原理、优缺点及其在不同光照和温度条件下的动态响应特性,同时提出一种改进的复合控制策略以提升系统在复杂环境下的跟踪精度与稳定性。通过仿真结果对比分析,验证了所提方法在快速性和准确性方面的优势,适用于光伏发电系统的高效能量转换控制。; 适合人群:具备一定C语言编程基础和电力电子知识背景,从事光伏系统开发、嵌入式控制或新能源技术研发的工程师及高校研究人员;工作年限1-3年的初级至中级研发人员尤为适合。; 使用场景及目标:①掌握电导增量法与扰动观察法在实际光伏系统中的实现机制与切换逻辑;②学习如何在Plecs中搭建MPPT控制系统仿真模型;③实现自动全局搜索以避免传统算法陷入局部峰值问题,提升复杂工况下的最大功率追踪效率;④为光伏逆变器或太阳能充电控制器的算法开发提供技术参考与实现范例。; 阅读建议:建议读者结合文中提供的C语言算法逻辑与Plecs仿真模型同步学习,重点关注算法判断条件、步长调节策略及仿真参数设置。在理解基本原理的基础上,可通过修改光照强度、温度变化曲线等外部扰动因素,进一步测试算法鲁棒性,并尝试将其移植到实际嵌入式平台进行实验验证。
【无人机协同】动态环境下多无人机系统的协同路径规划与防撞研究(Matlab代码实现)​ 内容概要:本文围绕动态环境下多无人机系统的协同路径规划与防撞问题展开研究,提出基于Matlab的仿真代码实现方案。研究重点在于在复杂、动态环境中实现多无人机之间的高效协同飞行与避障,涵盖路径规划算法的设计与优化,确保无人机集群在执行任务过程中能够实时规避静态障碍物与动态冲突,保障飞行安全性与任务效率。文中结合智能优化算法,构建合理的成本目标函数(如路径长度、飞行高度、威胁规避、转弯角度等),并通过Matlab平台进行算法验证与仿真分析,展示多机协同的可行性与有效性。; 适合人群:具备一定Matlab编程基础,从事无人机控制、路径规划、智能优化算法研究的科研人员及研究生。; 使用场景及目标:①应用于灾害救援、军事侦察、区域巡检等多无人机协同任务场景;②目标是掌握多无人机系统在动态环境下的路径规划与防撞机制,提升协同作业能力与自主决策水平;③通过Matlab仿真深入理解协同算法的实现逻辑与参数调优方法。; 阅读建议:建议结合文中提供的Matlab代码进行实践操作,重点关注目标函数设计、避障策略实现与多机协同逻辑,配合仿真结果分析算法性能,进一步可尝试引入新型智能算法进行优化改进。
将以下代码的运行修改为将一个文件夹下所有图片的所有71个值计算并保存在表格里,每一个图片一行 import numpy as np # from skimage.feature import greycomatrix, greycoprops # from skimage.feature import greycomatrix, greycoprops # from skimage.feature import graycomatrix, graycoprops import cv2 from skimage import io import matplotlib.pyplot as plt from skimage.feature.texture import graycomatrix, graycoprops import pywt from skimage.feature import local_binary_pattern from skimage.color import rgb2gray def extract_glcm_features(image): # 将图像转换为灰度 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 计算灰度共生矩阵,设置距离为1,角度为0度,使用4个方向(0°, 45°, 90°, 135°) glcm = graycomatrix(gray_image, distances=[1], angles=[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], symmetric=True, normed=True) # 提取GLCM特征,比如对比度、同质性、能量、相关性 contrast = graycoprops(glcm, 'contrast') homogeneity = graycoprops(glcm, 'homogeneity') energy = graycoprops(glcm, 'energy') correlation = graycoprops(glcm, 'correlation') # print(contrast,homogeneity,energy,correlation) # 返回特征向量 # glcm_features = np.hstack([contrast, homogeneity, energy, correlation]) # entropy = -np.sum(glcm * np.log2(glcm + (glcm == 0))) # correlation = skf.greycoprops(glcm, 'correlation')[0, 0] # variance = np.var(gray_image) glcm_features = np.hstack([contrast, homogeneity, energy, correlation]) return np.squeeze(glcm_features) # 提取灰度差分统计法纹理特征 def extract_gray_diff_stats(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 计算水平、垂直、对角线上的灰度差分 horizontal_diff = np.diff(gray_image, axis=1) vertical_diff = np.diff(gray_image, axis=0) diagonal_diff = np.diff(gray_image[:-1, :-1], axis=1) # 计算差分统计特征 mean_horizontal = np.mean(horizontal_diff) std_horizontal = np.std(horizontal_diff) mean_vertical = np.mean(vertical_diff) std_vertical = np.std(vertical_diff) mean_diagonal = np.mean(diagonal_diff) std_diagonal = np.std(diagonal_diff) features = np.array([mean_horizontal,std_horizontal,mean_vertical,std_vertical,mean_diagonal,std_diagonal]) # features = { # 'mean_horizontal_diff': mean_horizontal, # 'std_horizontal_diff': std_horizontal, # 'mean_vertical_diff': mean_vertical, # 'std_vertical_diff': std_vertical, # 'mean_diagonal_diff': mean_diagonal, # 'std_diagonal_diff': std_diagonal # } return features # 提取一阶统计特征 def extract_first_order_stats(image): # 灰度图像 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 二值化处理(如需要可调整阈值) _, binary_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY) # 前景像素占比 foreground_ratio = np.sum(binary_image == 255) / binary_image.size # 灰度均值、标准差、均方根 mean_gray = np.mean(gray_image) std_gray = np.std(gray_image) rms_gray = np.sqrt(np.mean(np.square(gray_image))) # features = { # 'foreground_ratio': foreground_ratio, # 'mean_gray': mean_gray, # 'std_gray': std_gray, # 'rms_gray': rms_gray # } features = np.array([mean_gray, std_gray, rms_gray]) return features def extract_tamura_features(image): # 将图像转换为灰度 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 粗糙度(coarseness):可以基于像素值的变化来计算 coarseness = np.var(gray_image) # 方差表示粗糙度的一个近似 # 对比度(contrast):标准差 contrast = np.std(gray_image) # 方向性(directionality):可以通过梯度方向直方图来近似 gx = cv2.Sobel(gray_image, cv2.CV_64F, 1, 0, ksize=3) gy = cv2.Sobel(gray_image, cv2.CV_64F, 0, 1, ksize=3) magnitude, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True) directionality = np.histogram(angle, bins=30, range=(0, 360))[0] # 将这些特征组合成一个向量 # print(coarseness, contrast, directionality) tamura_features = np.hstack([coarseness, contrast, directionality]) # print(tamura_features) # print(coarseness.shape, contrast.shape, directionality.shape) # tamura_features = np.hstack([coarseness, contrast, directionality]) return tamura_features def extract_wavelet_features(image): # 使用小波变换分解图像 coeffs = pywt.wavedec2(image, 'bior1.3', level=1) cA, (cH, cV, cD) = coeffs[0], coeffs[1] # 提取各个子带的统计特征(均值、标准差) wavelet_features = np.array([ np.mean(cA), np.std(cA), np.mean(cH), np.std(cH), # np.mean(cV), np.std(cV), # np.mean(cD), np.std(cD) ]) return wavelet_features def extract_lbp_features(image, num_points=8, radius=1): if len(image.shape) == 3: # 如果是 RGB 图像 image = rgb2gray(image) # 转换为灰度图像 # 计算 LBP 图像 lbp_image = local_binary_pattern(image, num_points, radius, method='uniform') # 提取直方图特征 hist, _ = np.histogram(lbp_image, bins=np.arange(0, num_points + 3), range=(0, num_points + 2)) hist = hist.astype("float") hist /= (hist.sum() + 1e-7) # 归一化 return hist def extract_fourier_features(image): # 对图像进行傅里叶变换 f = np.fft.fft2(image) fshift = np.fft.fftshift(f) magnitude_spectrum = 20 * np.log(np.abs(fshift)) # 提取频域特征(均值、标准差) fourier_features = np.array([ np.mean(magnitude_spectrum), np.std(magnitude_spectrum) ]) return fourier_features # 主函数:提取所有特征 def extract_all_features(image): glcm_features = extract_glcm_features(image) # print(glcm_features.shape) diff_features = extract_gray_diff_stats(image) # print(diff_features.shape) first_features = extract_first_order_stats(image) # print(first_features.shape) tamura_features = extract_tamura_features(image) # print(tamura_features.shape) # 合并所有特征 # features = np.array([contrast,homogeneity,energy,correlation,entropy,mean_horizontal,std_horizontal,mean_vertical,std_vertical,mean_diagonal,\ # mean_gray, std_gray, rms_gray]) features_all = np.hstack([glcm_features, diff_features, first_features, tamura_features]) # all_features = {**glcm_features, **gray_diff_features, **first_order_features} return features_all def extract_all_features_V2(image): glcm_features = extract_glcm_features(image) diff_features = extract_gray_diff_stats(image) first_features = extract_first_order_stats(image) tamura_features = extract_tamura_features(image) # 新增的小波变换特征 wavelet_features = extract_wavelet_features(image) # 新增的 LBP 特征 lbp_features = extract_lbp_features(image) # 新增的傅里叶变换特征 fourier_features = extract_fourier_features(image) # 合并所有特征 features_all = np.hstack([ glcm_features, diff_features, first_features, tamura_features, wavelet_features, lbp_features ]) # features_all = np.hstack([glcm_features, diff_features, first_features, tamura_features, # wavelet_features, lbp_features, fourier_features]) return features_all # 示例用法 # 读取图像 image = cv2.imread('0/grind_2_CCD_bottom_image_1.png') print(image.shape) # "/home/liuhuaxin/surface_roughness_V2/dataset/Dataset_multimodal_V3/train/image_ccd/grind_12_CCD_bottom_image_1.png" # image = cv2.imread('image_path.jpg') features = extract_all_features_V2(image) print(features.shape) print(features) # for key, value in features.item(): # print(f'{key}: {value}')
11-29
你当前的代码已经实现了从单张图像中提取多种纹理和统计特征(GLCM、灰度差分、一阶统计、Tamura、小波、LBP、傅里叶等),现在你想将其**扩展为处理一个文件夹下的所有图片**,并对每张图片提取完整的特征向量(共71个值),然后将结果保存到一个表格文件(如 CSV)中,**每张图片对应一行**。 --- ### ✅ 修改目标 - 遍历指定文件夹中的所有图像文件(支持常见格式:`.png`, `.jpg`, `.jpeg`, `.bmp` 等) - 对每张图像提取 `extract_all_features_V2(image)` 返回的特征 - 将所有图像的特征合并成一个二维表格(行:图像,列:特征 + 文件名) - 保存为 `features.csv` --- ### ✅ 补充说明:为什么是 71 个特征? 我们先验证一下你的 `extract_all_features_V2` 是否真的输出 **71 维特征**: ```python glcm_features: (4 directions) × 4 metrics = 16 diff_features: 6 first_features: 3 tamura_features: 1 (coarseness) + 1 (contrast) + 30 (directionality hist) = 32 wavelet_features: 4 (mean/std of cA, cH) lbp_features: 9 (for num_points=8 → uniform LBP has 9 bins) fourier_features: 2 (但注意:目前没加入!) → 当前 total = 16+6+3+32+4+9 = 70 ❌ ``` > ⚠️ 所以你现在实际只有 **70** 维。如果你说“71”,可能是漏加了 `fourier_features` 或者方向性 bin 数不同。 我们将: - 保留现有结构 - 明确维度 - 可选加入 `fourier_features` 达到 72 或根据需求调整 但为了匹配你说的 **71维**,我们假设你是有意设置的,比如 `directionality` 是 29-bin?所以我们先按实际计算为准,并打印 shape 调试。 --- ## ✅ 完整修改后的代码(批量处理 + 保存 CSV) ```python import os import cv2 import numpy as np import pandas as pd from skimage.feature.texture import graycomatrix, graycoprops from skimage.feature import local_binary_pattern from skimage.color import rgb2gray import pywt # --------------------- 特征提取函数(保持不变)--------------------- def extract_glcm_features(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) glcm = graycomatrix(gray_image, distances=[1], angles=[0, np.pi/4, np.pi/2, 3*np.pi/4], symmetric=True, normed=True) contrast = graycoprops(glcm, 'contrast')[0] homogeneity = graycoprops(glcm, 'homogeneity')[0] energy = graycoprops(glcm, 'energy')[0] correlation = graycoprops(glcm, 'correlation')[0] glcm_features = np.hstack([contrast, homogeneity, energy, correlation]) return glcm_features # 4×4 = 16 dim def extract_gray_diff_stats(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) horizontal_diff = np.diff(gray_image, axis=1) vertical_diff = np.diff(gray_image, axis=0) diagonal_diff = np.diff(gray_image[:-1, :-1], axis=1) features = [ np.mean(horizontal_diff), np.std(horizontal_diff), np.mean(vertical_diff), np.std(vertical_diff), np.mean(diagonal_diff), np.std(diagonal_diff) ] return np.array(features) # 6 dim def extract_first_order_stats(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) mean_gray = np.mean(gray_image) std_gray = np.std(gray_image) rms_gray = np.sqrt(np.mean(np.square(gray_image))) return np.array([mean_gray, std_gray, rms_gray]) # 3 dim def extract_tamura_features(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) coarseness = np.var(gray_image) contrast = np.std(gray_image) gx = cv2.Sobel(gray_image, cv2.CV_64F, 1, 0, ksize=3) gy = cv2.Sobel(gray_image, cv2.CV_64F, 0, 1, ksize=3) magnitude, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True) directionality_hist = np.histogram(angle, bins=30, range=(0, 360))[0] return np.hstack([coarseness, contrast, directionality_hist]) # 1+1+30 = 32 dim def extract_wavelet_features(image): if len(image.shape) == 3: image = rgb2gray(image) coeffs = pywt.wavedec2(image, 'bior1.3', level=1) cA, (cH, cV, cD) = coeffs[0], coeffs[1] return np.array([ np.mean(cA), np.std(cA), np.mean(cH), np.std(cH) ]) # 4 dim def extract_lbp_features(image, num_points=8, radius=1): if len(image.shape) == 3: image = rgb2gray(image) lbp_image = local_binary_pattern(image, num_points, radius, method='uniform') n_bins = int(lbp_image.max() + 1) hist, _ = np.histogram(lbp_image, bins=n_bins, range=(0, n_bins), density=True) return hist # typically 9 bins for uniform LBP with P=8 def extract_fourier_features(image): if len(image.shape) == 3: image = rgb2gray(image) f = np.fft.fft2(image) fshift = np.fft.fftshift(f) magnitude_spectrum = 20 * np.log(np.abs(fshift) + 1e-10) return np.array([np.mean(magnitude_spectrum), np.std(magnitude_spectrum)]) # 2 dim def extract_all_features_V2(image): glcm = extract_glcm_features(image) diff = extract_gray_diff_stats(image) first = extract_first_order_stats(image) tamura = extract_tamura_features(image) wavelet = extract_wavelet_features(image) lbp = extract_lbp_features(image) # fourier = extract_fourier_features(image) # 可选加入 all_features = np.hstack([glcm, diff, first, tamura, wavelet, lbp]) # 总计: 16+6+3+32+4+9 = 70 return all_features # --------------------- 批量处理主程序 --------------------- def batch_extract_features(folder_path, output_csv='image_features.csv'): # 支持的图像格式 supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.tif') # 存储结果 results = [] # 获取所有图像文件 for filename in sorted(os.listdir(folder_path)): if not filename.lower().endswith(supported_formats): continue file_path = os.path.join(folder_path, filename) try: image = cv2.imread(file_path) if image is None: print(f"[警告] 无法读取图像: {filename}") continue # 提取特征 features = extract_all_features_V2(image) # 检查是否确实是 70 或预期维度 if len(features) != 70: print(f"[警告] 特征长度异常 ({len(features)}): {filename}") # 构造数据行:文件名 + 所有特征 row = {'filename': filename} for i, feat in enumerate(features): row[f'feature_{i+1}'] = feat results.append(row) print(f"已处理: {filename} -> 特征维度: {len(features)}") except Exception as e: print(f"[错误] 处理 {filename} 时出错: {str(e)}") # 转为 DataFrame 并保存 df = pd.DataFrame(results) df.to_csv(output_csv, index=False) print(f"\n✅ 所有图像特征提取完成,已保存至: {output_csv}") print(f"总计处理图像数量: {len(df)}") if len(df) > 0: print(f"特征总数(不含文件名): {len(df.columns) - 1}") return df # ===================== 使用示例 ===================== if __name__ == "__main__": folder_path = "0" # 替换为你的图像文件夹路径 output_csv = "image_features.csv" df = batch_extract_features(folder_path, output_csv) ``` --- ### ✅ 输出示例(CSV 内容): | filename | feature_1 | feature_2 | ... | feature_70 | |---------|-----------|----------|-----|------------| | grind_2_CCD_bottom_image_1.png | 0.02 | 0.95 | ... | 0.003 | --- ### ✅ 代码解释 | 模块 | 功能 | |------|------| | `os.listdir` + 后缀判断 | 遍历文件夹并筛选图像文件 | | `cv2.imread` | 读取图像 | | 异常捕获 | 跳过损坏或无法读取的图像 | | `pandas.DataFrame` | 构建表格结构 | | 列命名 `feature_1` ~ `feature_70` | 清晰标识每个特征维度 | | 自动跳过非图像文件 | 更健壮 | --- ### ✅ 如何达到 71 维? 如果你想让总特征数为 **71**,可以: #### 方法一:加入傅里叶特征(+2 → 共 72) ```python all_features = np.hstack([glcm, diff, first, tamura, wavelet, lbp, extract_fourier_features(image)]) ``` #### 方法二:减少方向性直方图 bin 数为 29(32→31)+ 不加 Fourier → 得 70 → 再加一个全局均值 → 71 或者你可以显式命名每一列以便后续分析(推荐进阶使用)。 --- ### ✅ 进阶建议 - 添加进度条:使用 `tqdm` - 多线程加速:`concurrent.futures.ThreadPoolExecutor` - 特征标准化 / PCA 降维(用于可视化或建模) - 加入标签(如果有分类任务) --- ### ✅ 示例运行命令 ```bash python extract_batch.py ``` 确保安装依赖: ```bash pip install opencv-python scikit-image scipy pywavelets pandas matplotlib ``` --- ##
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值