  Future<void> takePhoto() async {
    try {
      await _initializeControllerFuture;

      // 写真を撮影する
      final photo = await _controller.takePicture();
      // 写真を読み込み640×640にリサイズ
      final image = await _loadAndAdjustImage(photo.path);
      // Uint8List型に変換
      final imageData = image.getBytes(order: img.ChannelOrder.rgb);
      final width = image.width;
      final height = image.height;

      // 推論実行
      int startTime = DateTime.now().millisecondsSinceEpoch;
      final results = _model.run(imageData, width, height);
      int endTime = DateTime.now().millisecondsSinceEpoch;
      int processingTime = (endTime - startTime);

      // 推論結果を画面表示用クラス（ResultPage）へ渡す
      if (!mounted) return;
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => ResultPage(
                results: results,
                image: image,
                processingTime: processingTime)),
      );
    } catch (e) {
      // Handle errors here.
    }
  }

  Future<img.Image> _loadAndAdjustImage(String filePath) async {
    // 写真をモデル入力サイズに調整する
    final originalFile = File(filePath);
    final originalBytes = await originalFile.readAsBytes();

    final decodedImage = img.decodeImage(originalBytes);
    if (decodedImage == null) {
      throw Exception("画像のデコードに失敗しました");
    }

    final w = decodedImage.width;
    // 幅x幅の正方形に切り抜き
    final cropped = img.copyCrop(decodedImage, x: 0, y: 0, width: w, height: w);
    // 640×640にリサイズ
    final resized = img.copyResize(cropped, width: 640, height: 640);
    return resized;
  }
