Android Media Scanner工作流程及原理

MediaScanner-MediaPrivider-插拔U盘多媒体扫描并优化 有些行业上,需要涉及到Android系统插拔U盘并扫描数据,如音乐、视频并播放。原生系统MediaScanner扫描,MediaStore通过ContentProvider读取,也是可行的。 阅读详情
下面是系统 图
      1.jpg

MediaScannerReceiver 会在任何的 ACTION_BOOT_COMPLETED, ACTION_MEDIA_MOUNTED 或ACTION_MEDIA_SCANNER_SCAN_FILE 意图( intent )发出的时候启动。因为解析媒体文件 的元数据 或许会需要很长时间 ,所以MediaScannerReceiver 会启动 MediaScannerService 。


MediaScannerService 调用一个公用类 MediaScanner 去处理真正的工作。 MediaScannerReceiver 维持两种扫描目录:一种是内部卷(internal volume )指向 $(ANDROID_ROOT)/media. 另一种是外部卷( external volume )指向 $(EXTERNAL_STORAGE).

扫描和解析工作位于 JAVA 层和 C++ 层。 JAVA 层是启动器。 MediaScanner 扫描所有目录,如下步骤:


1.JAVA 层初始化

在这一步骤中,它会根据目录是在内部卷还是外部卷打开不同的数据库 。

2.Java 层预扫描

首先清除文件和播放 列表的缓存条目。然后根据 MediaProvider 返回的请求结果生成新文件和播放列表缓存条目。

3.C++ 层处理目录

列举出所有文件和特定的所有子目录(如果子目录包含一个 .nomedia 隐藏文件,则不会被列举出来。)。被列举的文件是根据文件扩展来判断文件是否被支持。如果支持这种文件扩展, C++ 层就会回调到 JAVA 层扫描文件。这种扩展就会被扫描到 MediaFile.java 中列出。下面是支持的文件扩展列表。

/* Audio */ 


addFileType("MP3", FILE_TYPE_MP3, "audio/mpeg"); 


addFileType("M4A", FILE_TYPE_M4A, "audio/mp4"); 


addFileType("WAV", FILE_TYPE_WAV, "audio/x-wav"); 


addFileType("AMR", FILE_TYPE_AMR, "audio/amr"); 


addFileType("AWB", FILE_TYPE_AWB, "audio/amr-wb"); 


addFileType("WMA", FILE_TYPE_WMA, "audio/x-ms-wma"); 


addFileType("OGG", FILE_TYPE_OGG, "application/ogg"); 


addFileType("MID", FILE_TYPE_MID, "audio/midi"); 


addFileType("XMF", FILE_TYPE_MID, "audio/midi"); 


addFileType("RTTTL", FILE_TYPE_MID, "audio/midi"); 


addFileType("SMF", FILE_TYPE_SMF, "audio/sp-midi"); 


addFileType("IMY", FILE_TYPE_IMY, "audio/imelody"); 





/* Video */ 


addFileType("MP4", FILE_TYPE_MP4, "video/mp4"); 


addFileType("M4V", FILE_TYPE_M4V, "video/mp4"); 


addFileType("3GP", FILE_TYPE_3GPP, "video/3gpp"); 


addFileType("3GPP", FILE_TYPE_3GPP, "video/3gpp"); 


addFileType("3G2", FILE_TYPE_3GPP2, "video/3gpp2"); 


addFileType("3GPP2", FILE_TYPE_3GPP2, "video/3gpp2"); 


addFileType("WMV", FILE_TYPE_WMV, "video/x-ms-wmv"); 





/* Image */ 


addFileType("JPG", FILE_TYPE_JPEG, "image/jpeg"); 


addFileType("JPEG", FILE_TYPE_JPEG, "image/jpeg"); 


addFileType("GIF", FILE_TYPE_GIF, "image/gif"); 


addFileType("PNG", FILE_TYPE_PNG, "image/png"); 


addFileType("BMP", FILE_TYPE_BMP, "image/x-ms-bmp"); 


addFileType("WBMP", FILE_TYPE_WBMP, "image/vnd.wap.wbmp"); 





/* Audio Play List */ 


addFileType("M3U", FILE_TYPE_M3U, "audio/x-mpegurl"); 


addFileType("PLS", FILE_TYPE_PLS, "audio/x-scpls"); 


addFileType("WPL", FILE_TYPE_WPL, "application/vnd.ms-wpl"); 



 

4.Java 层扫描文件


    a ) Java 层开始文件


首先它忽略一些 MacOS 和 Windows Media Player 特殊的文件。然后它会查看被扫描的文件是否已经存在于缓存条目中,如果存在,它会检查文件上次修改的时间是否改变。最后它返回该文件是否需要进一步处理的结果。如果不需要,接下来的两步不会执行。


    b)C++ 层扫描文件


不是所有的文件都需要交给 C++ 层解析成元数据。只有下面的文件类型会被解析,注意,这里不处理 image 文件。

if (mFileType == MediaFile.FILE_TYPE_MP3 || 


mFileType == MediaFile.FILE_TYPE_MP4 || 


mFileType == MediaFile.FILE_TYPE_M4A || 


mFileType == MediaFile.FILE_TYPE_3GPP || 


mFileType == MediaFile.FILE_TYPE_3GPP2 || 


mFileType == MediaFile.FILE_TYPE_OGG || 


mFileType == MediaFile.FILE_TYPE_MID || 


mFileType == MediaFile.FILE_TYPE_WMA) { 


 



对于被解析的元数据信息, C++ 层会回调到 JAVA 层的 handleStringTag 。 Java 层会记录它的 name/value 信息。


    c)Java 层结束文件


   最后根据上一步解析出的值, Java 层会更新相应的 MeidaProvider 产生的数据库表。


5.Java 层发送扫描


    到目前为止,所有文件已经被扫描,它最后会检查文件和播放列表缓存条目,看是否所有项仍然存在于文件系统。如果有空条目,则会从数据库中删除。这样它能够保持数据库和文件系统的一致性。


    其他的应用 程序 通过接收 MediaScannerService 发出的 ACTION_MEDIA_SCANNER_STARTED 和ACTION_MEDIA_SCANNER_FINISHED 意图能够知道什么时候扫描操作开始和结束。


MediaScanner



之所以拿MediaScanner开刀 因为想借用系统的Media Scan 工具  通过Intent直接调用系统的



[步骤]


1. 下载并安装Git 过程略 网络上很多

2. 得到该功能的模块地址并使用Git下载之   地址:git://android.git.kernel.org/platform/packages/providers/MediaProvider.git

3.  分析源代码:


- AndroidManifest.xml :  各组件属性描述文件


- MediaProvider : extends ContentProvider  使用SQLiteDatabase 保存查询数据 action="content://media"


- MediaScannerCursor.java


- MediaScannerReceiver : extends BroadcastReceiver   用于接收指定Broadcast: BOOT_COMPLETED MEDIA_MOUNTED MEDIA_SCANNER_SCAN_FILE 并启动 MediaScannerService 开始扫描


- MediaScannerService : extends Service   执行具体的扫描工作


- MediaThumbRequest

4. 鉴于 并不打算自行实现多媒体扫描 因此 此次重点研究对象:MediaScannerReceiver

5. MediaScannerReceiver 代码


Java代码

  1. public   class  MediaScannerReceiver  extends  BroadcastReceiver  
  2. {  
  3.     private   final   static  String TAG =  "MediaScannerReceiver" ;  
  4.   
  5.     @Override   
  6.     public   void  onReceive(Context context, Intent intent) {  
  7.         String action = intent.getAction();  
  8.         Uri uri = intent.getData();  
  9.         String externalStoragePath = Environment.getExternalStorageDirectory().getPath();  
  10.   
  11.         if  (action.equals(Intent.ACTION_BOOT_COMPLETED)) {  
  12.             // scan internal storage   
  13.             scan(context, MediaProvider.INTERNAL_VOLUME);  
  14.         } else  {  
  15.             if  (uri.getScheme().equals( "file" )) {  
  16.                 // handle intents related to external storage   
  17.                 String path = uri.getPath();  
  18.                 if  (action.equals(Intent.ACTION_MEDIA_MOUNTED) &&   
  19.                         externalStoragePath.equals(path)) {  
  20.                     scan(context, MediaProvider.EXTERNAL_VOLUME);  
  21.                 } else   if  (action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) &&  
  22.                         path != null  && path.startsWith(externalStoragePath +  "/" )) {  
  23.                     scanFile(context, path);  
  24.                 }  
  25.             }  
  26.         }  
  27.     }  
  28.   
  29.     private   void  scan(Context context, String volume) {  
  30.         Bundle args = new  Bundle();  
  31.         args.putString("volume" , volume);  
  32.         context.startService(  
  33.                 new  Intent(context, MediaScannerService. class ).putExtras(args));  
  34.     }      
  35.   
  36.     private   void  scanFile(Context context, String path) {  
  37.         Bundle args = new  Bundle();  
  38.         args.putString("filepath" , path);  
  39.         context.startService(  
  40.                 new  Intent(context, MediaScannerService. class ).putExtras(args));  
  41.     }      
  42. }  

Java代码


  1. public class MediaScannerReceiver extends BroadcastReceiver
  2. {
  3.     private final static String TAG = "MediaScannerReceiver";

  4.     @Override
  5.     public void onReceive(Context context, Intent intent) {
  6.         String action = intent.getAction();
  7.         Uri uri = intent.getData();
  8.         String externalStoragePath = Environment.getExternalStorageDirectory().getPath();

  9.         if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
  10.             // scan internal storage
  11.             scan(context, MediaProvider.INTERNAL_VOLUME);
  12.         } else {
  13.             if (uri.getScheme().equals("file")) {
  14.                 // handle intents related to external storage
  15.                 String path = uri.getPath();
  16.                 if (action.equals(Intent.ACTION_MEDIA_MOUNTED) &&
  17.                         externalStoragePath.equals(path)) {
  18.                     scan(context, MediaProvider.EXTERNAL_VOLUME);
  19.                 } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) &&
  20.                         path != null && path.startsWith(externalStoragePath + "/")) {
  21.                     scanFile(context, path);
  22.                 }
  23.             }
  24.         }
  25.     }

  26.     private void scan(Context context, String volume) {
  27.         Bundle args = new Bundle();
  28.         args.putString("volume", volume);
  29.         context.startService(
  30.                 new Intent(context, MediaScannerService.class).putExtras(args));
  31.     }   

  32.     private void scanFile(Context context, String path) {
  33.         Bundle args = new Bundle();
  34.         args.putString("filepath", path);
  35.         context.startService(
  36.                 new Intent(context, MediaScannerService.class).putExtras(args));
  37.     }   
  38. }

6.   根据以上代码得知:


-  当系统启动完毕 会扫描一次


-  当 ACTION_MEDIA_MOUNTED ACTION_MEDIA_SCANNER_SCAN_FILE 也会扫描



7.  如何调用系统MediaScanner 进行扫描



- 通过 Intent.ACTION_MEDIA_MOUNTED 进行全扫描



Java代码

  1. public   void  allScan(){  
  2.         sendBroadcast(new  Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse( "file://"   
  3.                 + Environment.getExternalStorageDirectory())));  
  4.     }  

Java代码


  1. public void allScan(){
  2.             sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
  3.                 + Environment.getExternalStorageDirectory())));
  4.     }


通过 Intent.ACTION_MEDIA_SCANNER_SCAN_FILE 扫描某个文件


Java代码


  1. public   void  fileScan(String fName){  
  2.         Uri data = Uri.parse("file:///" +fName);  
  3.         sendBroadcast(new  Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));  
  4.     }  

Java代码


  1. public void fileScan(String fName){
  2.             Uri data = Uri.parse("file:///"+fName);
  3.             sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
  4.     }


补充: 上述方法是不支持对文件夹的 即:Uri data 必须是 文件的Uri  如果是文件夹的 其不会起作用的 切记!



- 如何扫描某文件夹下所有文件 难道就不可以么? 当然不 借助于Intent.ACTION_MEDIA_SCANNER_SCAN_FILE


我们可以这么做: 取出该文件夹下的所有子文件 如其是文件且类型符合条件 就取出该文件目录 以 Intent.ACTION_MEDIA_SCANNER_SCAN_FILE方式发送至MediaScannerReceiver   若其为文件夹 则迭代查询之    故实现为:

Java代码

  1. public   void  fileScan(String file){  
  2.         Uri data = Uri.parse("file://" +file);  
  3.          
  4.         Log.d("TAG" , "file:" +file);  
  5.         sendBroadcast(new  Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));  
  6.     }  
  7.       
  8.     public   void  folderScan(String path){  
  9.         File file = new  File(path);  
  10.          
  11.         if (file.isDirectory()){  
  12.             File[] array = file.listFiles();  
  13.               
  14.             for ( int  i= 0 ;i<array.length;i++){  
  15.                 File f = array[i];  
  16.                   
  17.                 if (f.isFile()){ //FILE TYPE   
  18.                     String name = f.getName();  
  19.                      
  20.                     if (name.contains( ".mp3" )){  
  21.                         fileScan(f.getAbsolutePath());  
  22.                     }  
  23.                 }  
  24.                 else  { //FOLDER TYPE   
  25.                     folderScan(f.getAbsolutePath());  
  26.                 }  
  27.             }  
  28.         }  
  29.     }  

Java代码

  1. public void fileScan(String file){
  2.             Uri data = Uri.parse("file://"+file);
  3.             
  4.             Log.d("TAG","file:"+file);
  5.             sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
  6.     }
  7.    
  8.     public void folderScan(String path){
  9.             File file = new File(path);
  10.             
  11.             if(file.isDirectory()){
  12.                     File[] array = file.listFiles();
  13.                     
  14.                     for(int i=0;i<array.length;i++){
  15.                             File f = array[i];
  16.                            
  17.                             if(f.isFile()){//FILE TYPE
  18.                                     String name = f.getName();
  19.                                     
  20.                                     if(name.contains(".mp3")){
  21.                                             fileScan(f.getAbsolutePath());
  22.                                     }
  23.                             }
  24.                             else {//FOLDER TYPE
  25.                                     folderScan(f.getAbsolutePath());
  26.                             }
  27.                     }
  28.             }
  29.     }


8. 鉴于多数人并不关心其原理 仅关系如何使用 故 总结如下:



-   扫描全部 我猜测其在效率方面可能有点副作用

Java代码


  1. public   void  systemScan(){  
  2.         sendBroadcast(new  Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse( "file://"   
  3.                 + Environment.getExternalStorageDirectory())));  
  4.     }

Java代码


  1. public void systemScan(){  
  2.         sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"  
  3.                 + Environment.getExternalStorageDirectory())));  
  4.     }  


扫描某个文件  参数:填入该文件的路径



Java代码


  1. public   void  fileScan(String file){  
  2.         Uri data = Uri.parse("file://" +file);  
  3.          
  4.         sendBroadcast(new  Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));  
  5.     }  

Java代码


  1. public void fileScan(String file){  
  2.         Uri data = Uri.parse("file://"+file);  
  3.          
  4.         sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));  
  5.     }

扫描文件夹 参数:填入该文件夹路径

Java代码



  1. public   void  fileScan(String file){  
  2.         Uri data = Uri.parse("file://" +file);  
  3.          
  4.         sendBroadcast(new  Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));  
  5.     }  
  6.       
  7.     public   void  folderScan(String path){  
  8.         File file = new  File(path);  
  9.          
  10.         if (file.isDirectory()){  
  11.             File[] array = file.listFiles();  
  12.               
  13.             for ( int  i= 0 ;i<array.length;i++){  
  14.                 File f = array[i];  
  15.                   
  16.                 if (f.isFile()){ //FILE TYPE   
  17.                     String name = f.getName();  
  18.                      
  19.                     if (name.contains( ".mp3" )){  
  20.                         fileScan(f.getAbsolutePath());  
  21.                     }  
  22.                 }  
  23.                 else  { //FOLDER TYPE   
  24.                     folderScan(f.getAbsolutePath());  
  25.                 }  
  26.             }  
  27.         }  
  28.     }


Java代码


  1. public void fileScan(String file){
  2.             Uri data = Uri.parse("file://"+file);
  3.            
  4.             sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
  5.     }
  6.    
  7.     public void folderScan(String path){
  8.             File file = new File(path);
  9.            
  10.             if(file.isDirectory()){
  11.                     File[] array = file.listFiles();
  12.                    
  13.                     for(int i=0;i<array.length;i++){
  14.                             File f = array[i];
  15.                            
  16.                             if(f.isFile()){//FILE TYPE
  17.                                     String name = f.getName();
  18.                                    
  19.                                     if(name.contains(".mp3")){
  20.                                             fileScan(f.getAbsolutePath());
  21.                                     }
  22.                             }
  23.                             else {//FOLDER TYPE
  24.                                     folderScan(f.getAbsolutePath());
  25.                             }
  26.                     }
  27.             }
  28.     }

【异常】OpenClaw网关仪表盘 pairing required 报错排查与解决方案 在OpenClaw网关仪表盘页面,完成WebSocket URL、网关令牌等必填项配置后,点击「连接」按钮尝试建立网关连接时,页面下方出现红色报错提示框,核心报错内容为,无法完成网关连接建立,且该报错在令牌配置正确、网络链路通畅的场景下仍会触发。该报错常见于非本地回环地址的访问场景,包括局域网远程访问、公网域名/IP访问、云服务器部署的网关远程管理等场景,本地127.0.0.1回环地址访问通常可正常连接。 阅读详情

相关推荐

window下迁移SVN仓库到新的windows服务器

window下迁移SVN仓库到新的windows服务器

Bertram的博客 4692

Android 发送系统广播ACTION_MEDIA_SCANNER_SCAN_FILE更新相册无效

把bitmap以png保存到手机本地,然后在相册中查看没有显示,但是在文件管理中却可以看到,4.4之后android提供了专门的API通知系统刷新制定路径,但是这个路径必须是Environment.getExternalStorageDirectory().getAbsolutePath() 开头,在保存成功后使用ACTION_MEDIA_SCANNER_SCAN_FILE这个广播更新却发现相册中...

xing_xiangrong的博客 1万+

目标检测技术的发展:从R-CNN、YOLO到DETR、DINO

OV-DINO的出现标志着在开放域目标检测领域的重大进步,其在处理未见过的物体类别时的能力得到了显著提升。这项技术对于需要适应未知或变化环境的应用具有重要意义,如自动驾驶、机器人视觉、安防监控等。

DeepAIedu的博客 2633

Android之媒体扫描

媒体扫描时序图 看了上面的时序图是否感觉比较绕,一会Java层,一会Native层。其实只要了解它们为什么这样做就比较好理解为什么这样做了。 第一次:扫描路径,查找媒体文件,找到媒体文件之后就告知上层 第二次:上层收到Native层已找到媒体文件后,经过初步处理,再调用Native层去解析媒体文件。解析完成后就把 解析数据上报给Java层,然后插入数据库。 媒体扫描之代码分析 MediaScannerReceiver.java @Override public void onReceive

Tony-jiang的博客 2178

学习笔记9--智能驾驶的功能安全设计之功能安全设计

本系列博客包括6个专栏,分别为:《自动驾驶技术概览》、《自动驾驶汽车平台技术基础》、《自动驾驶汽车定位技术》、《自动驾驶汽车环境感知》、《自动驾驶汽车决策与控制》、《自动驾驶系统设计及应用》。此专栏是关于《自动驾驶系统设计及应用》书籍的笔记.

FUXI_Willard 1796

缺陷检测-金属表面缺陷检测

1介绍 缺陷检测是工业视觉技术中最重要的组成部分。业务广泛,场景丰富,技术难点高、工作量大。针对不同的场景,选择不同的相机和

huneng1991的专栏 5250

Intent.ACTION_MEDIA_SCANNER_SCAN_FILE:扫描指定文件

1.启动MediaScanner服务,扫描媒体文件: 程序通过发送下面的Intent启动MediaScanner服务扫描指定的文件或目录: Intent.ACTION_MEDIA_SCANNER_SCAN_FILE:扫描指定文件 public void scanFileAsync(Context ctx, String filePath) { Intent s

Dream It Possible 1万+

手把手教你用OpenCore在Dell Optiplex 3060上安装黑苹果(含ALC255声卡修复)

本文提供了一份详尽的指南,教你如何在Dell Optiplex 3060微型台式机上安装黑苹果系统。文章重点解决了使用OpenCore引导时的核心配置,特别是针对Intel UHD 630核显的驱动优化和Realtek ALC255声卡的修复方案,旨在帮助用户打造一个稳定可用的macOS工作站。

weixin_29275257的博客 789

media scnner 工作流程

转自: http://blog.youkuaiyun.com/Innost/article/details/6083467 MediaScanner分析 一 MediaScannerService 多媒体扫描是从MediaScannerService开始的。这是一个单独的package。位于 packages/providers/MediaProvider:含以下java文件 l

东辉在线的专栏 1289

RH850从0搭建Autosar开发环境【6】- Davinci Configurator之CanIf模块配置详解(下)

RH850从0搭建Autosar开发环境【6】- Davinci Configurator之CanIf模块配置详解(下)

weixin_42412049的博客 2585

21天学会基于 Linux 的 NPU 固件开发--2.2 固件加载流程:request_firmware() 深度解析

本文深度解析Linux内核中NPU固件加载流程,重点剖析request_firmware()机制。内容涵盖:1)内核态与用户态的交互机制,包括同步/异步加载方式;2)NPU固件的特殊格式与加载逻辑;3)调试技巧与安全验证方案;4)提供最小化固件加载器实验。文章揭示了从文件系统到硬件初始化的完整链路,探讨了大模型时代面临的性能挑战与优化方案,如零拷贝加载技术,并提出了版本兼容性、断电恢复等关键问题的思考方向。

amy_mhd的博客 59

把 ABAP 开发对象装进 XML 行李箱:SAPlink 安装、插件、升级与协作迁移全指南

SAPlink是一款用于在SAP NetWeaver系统间导入导出ABAP对象的工具,特别适合临时协作、系统孤岛等场景。它通过XML文件(Slinkee和Nugget两种格式)传输开发对象,支持插件扩展多种对象类型。安装时需注意版本兼容性、权限和激活流程,使用时要区分覆盖选项的风险。相比正式运输系统,SAPlink更适用于快速共享、原型交付等非生产场景,但需配合命名规范和协作策略确保可维护性。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 156

android中的MediaScanner,MediaStore与MediaProvider

Android系统提供了对多媒体(图片、音乐、视频等)的统一处理机制,通过一套良好的框架实现了多媒体信息的扫描、存储、读取。用户可以基于这套框架非常方便的对多媒体信息进行处理。显儿易见这套框架主要包含了三部分: MediaScannerService(多媒体扫描服务) MediaStore(多媒体存储) MediaProvider(多媒体内容提供者) ...

yu890725gong的专栏 783

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

android源码解析------Media多媒体framework层分析

1.packages\providers\MediaProvider :含以下 java 文件 MediaProvider.java MediaScannerReceiver.java MediaScannerService.java MediaThumbRequest.java 2.查看该目录下AndroidMainfest.xml,从MediaScannerService...

guanhuaing 322

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

MediaScanner源码简单分析

前言 MediaScanner是Android系统中针对媒体文件的扫描过程,将储存空间中的媒体文件通过扫描的方式遍历并存储在数据库中,然后通过MediaProvider提供接口使用,在Android多媒体中占有很重要的位置。 源码位置 packages\providers\mediaproviderframeworks\base\media\java\android\mediaframeworks...

weixin_33958585的博客 228

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

【Android】MediaScanner 多媒体扫描流程

一、扫描方式 在4.4平台之前可以通过两种方式来扫描多媒体文件: 1、MediaScannerConnection.scanFile()方法,    MediaScannerConnection.scanFile(this,new String[] {Environment.getExternalStorageDirectory().getAbsolutePath()},null,   ...

乔培宸的博客 5865

从.9.png到品牌首映:探索Android开屏图背后的设计哲学与技术实现

本文探讨Android开屏页面的设计哲学与技术实现,重点解析.9.png格式的制作与多设备适配策略,并详细介绍在uni-app中集成自定义开屏页面的最佳实践。内容涵盖品牌一致性、性能优化及情感化设计,为开发者提供从技术部署到体验优化的完整解决方案。

java5的博客 910

mediascanner详解

OK, 我们现在开始来大概分析一下android framework中MediaScanner部分的流程,若大家发现分析过程中有错误,欢迎拍砖指正。 分析流程之前,我们先给自己定个要用MediaScanner解决的问题,这样我们才会有目标感,才知道我们要干什么。否则,干巴巴的分析流程,一般都会很容易的迷失在各种code的迷雾中。 我们这里要定的目标是:获取某个MP3文件的artist ...

weixin_34025051的博客 999
上一篇: Activity周期
下一篇: Android Binder机制(超级详尽)
火VVVVV
博客等级 码龄16年 87粉丝 3原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值