Harmony学习之AI能力集成

Harmony学习之AI能力集成

一、场景引入

小明正在开发一个智能相册应用,希望实现照片智能分类、人脸识别、场景识别等功能。传统开发需要集成复杂的AI算法和模型,而HarmonyOS提供了丰富的AI能力接口,让开发者可以轻松调用系统级的AI功能。

二、核心概念

1. HarmonyOS AI框架

HarmonyOS AI能力基于统一的AI引擎框架,提供以下核心功能:

  • 模型管理:支持模型加载、优化和部署
  • 推理引擎:提供高性能的AI推理能力
  • 算法仓库:内置多种预训练AI模型
  • 硬件加速:支持NPU、GPU等硬件加速

2. 主要AI能力分类

  • 图像识别:图像分类、目标检测、场景识别
  • 文本处理:文本识别、语义理解、翻译
  • 语音处理:语音识别、语音合成、声纹识别
  • 智能推荐:个性化推荐、内容理解

三、关键实现

1. 权限配置

在module.json5中申请AI能力权限:

// entry/src/main/module.json5
"requestPermissions": [
  {
    "name": "ohos.permission.MEDIA_LOCATION",
    "reason": "用于图片内容识别",
    "usedScene": {
      "abilities": ["EntryAbility"],
      "when": "inuse"
    }
  }
]

2. 图像分类实现

使用AI引擎进行图像分类:

// entry/src/main/ets/pages/ImageClassificationPage.ets
import ai from '@ohos.ai.engine';
import image from '@ohos.multimedia.image';

@Component
struct ImageClassificationPage {
  @State imagePixelMap: image.PixelMap | undefined = undefined;
  @State classificationResults: string[] = [];
  @State isLoading: boolean = false;

  // 初始化AI引擎
  private async initAIEngine(): Promise<ai.AIEngine> {
    try {
      const engine = ai.createAIImageClassification({
        mode: ai.ClassificationMode.CLASSIFICATION_MODE_SMART
      });
      return engine;
    } catch (error) {
      console.error('初始化AI引擎失败:', error);
      throw error;
    }
  }

  // 选择图片并进行分类
  async classifyImage() {
    if (!this.imagePixelMap) {
      console.error('请先选择图片');
      return;
    }

    this.isLoading = true;
    this.classificationResults = [];

    try {
      const engine = await this.initAIEngine();
      
      // 配置分类参数
      const config: ai.ImageClassificationConfig = {
        confidenceThreshold: 0.5, // 置信度阈值
        maxResults: 5 // 最多返回5个结果
      };

      // 执行图像分类
      const results = await engine.classify(this.imagePixelMap, config);
      
      this.classificationResults = results.map(item => 
        `${item.label}: ${(item.confidence * 100).toFixed(2)}%`
      );
    } catch (error) {
      console.error('图像分类失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 从相册选择图片
  async selectImage() {
    try {
      const picker = require('@ohos.file.picker');
      const photoSelectOptions = new picker.PhotoSelectOptions();
      photoSelectOptions.maxSelectNumber = 1;

      const photoPicker = new picker.PhotoViewPicker();
      const result = await photoPicker.select(photoSelectOptions);
      
      if (result.photoUris.length > 0) {
        const imageSource = image.createImageSource(result.photoUris[0]);
        this.imagePixelMap = await imageSource.createPixelmap();
        await imageSource.release();
      }
    } catch (error) {
      console.error('选择图片失败:', error);
    }
  }

  build() {
    Column() {
      Button('选择图片')
        .onClick(() => this.selectImage())
        .width('80%')
        .height(50)
        .margin(10)
      
      if (this.imagePixelMap) {
        Image(this.imagePixelMap)
          .width(200)
          .height(200)
          .borderRadius(10)
          .margin(10)
        
        Button('开始识别')
          .onClick(() => this.classifyImage())
          .width('80%')
          .height(50)
          .margin(10)
          .enabled(!this.isLoading)
      }

      if (this.isLoading) {
        LoadingProgress()
          .color(Color.Blue)
          .margin(20)
      }

      if (this.classificationResults.length > 0) {
        Column() {
          Text('识别结果:')
            .fontSize(18)
            .fontWeight(FontWeight.Bold)
            .margin(10)
          
          List() {
            ForEach(this.classificationResults, (item: string, index: number) => {
              ListItem() {
                Text(`${index + 1}. ${item}`)
                  .fontSize(16)
                  .padding(5)
              }
            })
          }
          .height(200)
        }
        .border({ width: 1, color: Color.Gray })
        .borderRadius(10)
        .padding(10)
        .margin(10)
      }
    }
  }
}

3. 文本识别实现

使用OCR能力识别图片中的文字:

// entry/src/main/ets/pages/TextRecognitionPage.ets
import ai from '@ohos.ai.engine';
import image from '@ohos.multimedia.image';

@Component
struct TextRecognitionPage {
  @State imagePixelMap: image.PixelMap | undefined = undefined;
  @State recognizedText: string = '';
  @State isLoading: boolean = false;

  // 初始化OCR引擎
  private async initOCREngine(): Promise<ai.OCR> {
    try {
      const engine = ai.createOCREngine();
      return engine;
    } catch (error) {
      console.error('初始化OCR引擎失败:', error);
      throw error;
    }
  }

  // 识别图片中的文字
  async recognizeText() {
    if (!this.imagePixelMap) {
      console.error('请先选择图片');
      return;
    }

    this.isLoading = true;
    this.recognizedText = '';

    try {
      const engine = await this.initOCREngine();
      
      // 配置OCR参数
      const config: ai.OCRConfig = {
        language: 'zh', // 中文识别
        mode: ai.OCRMode.FAST // 快速模式
      };

      // 执行文字识别
      const result = await engine.recognize(this.imagePixelMap, config);
      
      this.recognizedText = result.text;
    } catch (error) {
      console.error('文字识别失败:', error);
      this.recognizedText = '识别失败,请重试';
    } finally {
      this.isLoading = false;
    }
  }

  // 复制识别结果
  async copyToClipboard() {
    if (this.recognizedText) {
      const clipboard = require('@ohos.system.clipboard');
      await clipboard.setData({
        data: this.recognizedText
      });
      console.log('已复制到剪贴板');
    }
  }

  build() {
    Column() {
      Button('选择包含文字的图片')
        .onClick(() => this.selectImage())
        .width('80%')
        .height(50)
        .margin(10)
      
      if (this.imagePixelMap) {
        Image(this.imagePixelMap)
          .width(200)
          .height(200)
          .margin(10)
        
        Button('识别文字')
          .onClick(() => this.recognizeText())
          .width('80%')
          .height(50)
          .margin(10)
          .enabled(!this.isLoading)
      }

      if (this.isLoading) {
        LoadingProgress()
          .color(Color.Blue)
          .margin(20)
      }

      if (this.recognizedText) {
        Column() {
          Text('识别结果:')
            .fontSize(18)
            .fontWeight(FontWeight.Bold)
            .margin(10)
          
          Scroll() {
            Text(this.recognizedText)
              .fontSize(16)
              .padding(10)
          }
          .height(200)
          .border({ width: 1, color: Color.Gray })
          .borderRadius(5)
          .margin(10)
          
          Button('复制到剪贴板')
            .onClick(() => this.copyToClipboard())
            .width('80%')
            .height(40)
            .margin(10)
        }
      }
    }
  }
}

四、实战案例:智能相册应用

1. 智能照片分类

// entry/src/main/ets/utils/PhotoClassifier.ets
import ai from '@ohos.ai.engine';

export interface PhotoCategory {
  label: string;
  confidence: number;
  category: string;
}

export class PhotoClassifier {
  private engine: ai.AIEngine | null = null;

  // 初始化分类器
  async initialize(): Promise<void> {
    try {
      this.engine = ai.createAIImageClassification({
        mode: ai.ClassificationMode.CLASSIFICATION_MODE_SMART
      });
    } catch (error) {
      console.error('初始化照片分类器失败:', error);
      throw error;
    }
  }

  // 分类照片
  async classifyPhoto(pixelMap: image.PixelMap): Promise<PhotoCategory[]> {
    if (!this.engine) {
      await this.initialize();
    }

    try {
      const config: ai.ImageClassificationConfig = {
        confidenceThreshold: 0.3,
        maxResults: 3
      };

      const results = await this.engine!.classify(pixelMap, config);
      
      return results.map(item => ({
        label: item.label,
        confidence: item.confidence,
        category: this.mapToCategory(item.label)
      }));
    } catch (error) {
      console.error('照片分类失败:', error);
      return [];
    }
  }

  // 将标签映射到相册分类
  private mapToCategory(label: string): string {
    const categoryMap: Record<string, string> = {
      'person': '人物',
      'dog': '宠物',
      'cat': '宠物',
      'car': '交通',
      'building': '建筑',
      'tree': '自然',
      'flower': '自然',
      'food': '美食',
      'mountain': '风景',
      'sea': '风景',
      'beach': '风景'
    };

    return categoryMap[label.toLowerCase()] || '其他';
  }

  // 批量分类照片
  async batchClassify(photos: image.PixelMap[]): Promise<PhotoCategory[][]> {
    const results: PhotoCategory[][] = [];
    
    for (const photo of photos) {
      const categories = await this.classifyPhoto(photo);
      results.push(categories);
    }
    
    return results;
  }
}

五、最佳实践

1. 性能优化建议

// entry/src/main/ets/utils/AIPerformanceOptimizer.ets
export class AIPerformanceOptimizer {
  // 图片预处理(缩放到合适尺寸)
  static async preprocessImage(
    pixelMap: image.PixelMap, 
    targetWidth: number = 300
  ): Promise<image.PixelMap> {
    try {
      const scale = targetWidth / pixelMap.width;
      const operations: image.ImageOperation[] = [{
        operationType: image.OperationType.SCALE,
        scaleOptions: {
          scaleX: scale,
          scaleY: scale
        }
      }];

      return await image.applyOperations(pixelMap, operations);
    } catch (error) {
      console.error('图片预处理失败:', error);
      return pixelMap;
    }
  }

  // 模型预热
  static async warmUpModel(modelType: string): Promise<void> {
    try {
      const engine = ai.createAIEngine(modelType);
      // 使用空数据预热模型
      const dummyData = new ArrayBuffer(1024);
      await engine.process(dummyData);
      console.log(`${modelType} 模型预热完成`);
    } catch (error) {
      console.warn('模型预热失败:', error);
    }
  }
}

2. 错误处理机制

// entry/src/main/ets/utils/AIErrorHandler.ets
export class AIErrorHandler {
  // AI操作重试机制
  static async withRetry<T>(
    operation: () => Promise<T>,
    maxRetries: number = 2,
    delay: number = 1000
  ): Promise<T> {
    let lastError: Error | null = null;
    
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        return await operation();
      } catch (error) {
        lastError = error;
        console.warn(`AI操作失败,第${attempt}次重试:`, error);
        
        if (attempt < maxRetries) {
          await new Promise(resolve => setTimeout(resolve, delay * attempt));
        }
      }
    }
    
    throw lastError || new Error('AI操作失败');
  }

  // 检查AI服务可用性
  static async checkAIServiceAvailability(): Promise<boolean> {
    try {
      const aiService = ai.createAIService();
      const status = await aiService.getServiceStatus();
      return status === ai.ServiceStatus.SERVICE_AVAILABLE;
    } catch (error) {
      console.error('检查AI服务失败:', error);
      return false;
    }
  }
}

六、总结与行动建议

通过本篇文章,我们学习了HarmonyOS AI能力的集成方法。在实际开发中,建议:

  1. 选择合适的AI能力:根据应用需求选择最合适的AI功能,避免过度使用
  2. 性能优化:对大图片进行预处理,合理设置置信度阈值
  3. 错误处理:实现重试机制和降级策略,提升应用稳定性
  4. 隐私保护:AI处理涉及用户数据,需遵循隐私保护规范

建议读者在掌握基础功能后,进一步学习自定义模型部署、多模态AI融合等进阶内容,打造更智能的应用体验。

posted @ 2025-12-23 23:21  J_____P  阅读(0)  评论(0)    收藏  举报