Passio Nutrition-AI
  • Nutrition-AI SDK Overview
  • Guides
    • Nutrition AI SDK
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • iOS SDK Docs
      • Before getting started
      • Getting the ml models to the device
      • Run the demos first
      • Adding Passio SDK into your project
      • Initialize and configure the SDK
      • Start/Stop food detection
      • Food Recognition Delegate
      • Migration from SDK 1.4.X to 2.x
      • SDK API
      • Quick Start Guide
        • Installation
        • Configure the SDK (UIKit)
        • Recognise food using image
        • Food Details
    • Android SDK Docs
      • Getting started
        • Include the library
        • Camera
        • SDK Initialization and Configuration
        • Food detection session
        • Visual, Barcode and Packaged Food detection
        • Nutritional Database
        • Sandbox app
      • Troubleshooting on Android
      • Migration from SDK version 1.4.x to 2.x
      • Quick Start Guide
        • Importing the Android SDK to a project
        • Configure SDK and handle the result
        • RecognizeImageRemote
        • Food Details
    • React Native SDK Docs
      • Getting Started
        • Installation
        • SDK Initialization and Configuration
      • API Reference
        • configure & requestCameraAuthorization
        • recognizeImageRemote
        • searchForFood & searchForFoodSemantic
        • startFoodDetection
          • FoodDetectionEvent
        • fetchFoodItemForProductCode
        • fetchFoodItemForRefCode
        • fetchFoodItemForDataInfo
        • startNutritionFactsDetection
        • fetchFoodItemForPassioID
        • recognizeSpeechRemote
        • Fetch Nutrients
        • onDowloadingPassioModelCallBacks
        • detectFoodFromImageURI
        • addToPersonalization
        • updateLanguage
        • fetchHiddenIngredients
        • fetchVisualAlternatives
        • fetchPossibleIngredients
      • Properties
        • PassioFoodItem
        • PassioFoodDataInfo
        • PassioFoodAmount
        • PassioIngredient
        • PassioNutrients
        • UnitMass
        • ServingUnit
        • ServingSize
        • PassioSearchResult
        • NutritionFacts
        • PassioNutritionPreview
        • PassioSpeechRecognitionModel
        • PassioLogAction
        • PassioAdvisorFoodInfo
        • FoodCandidates
        • FoodDetectionEvent
        • NutritionDetectionEvent
        • DetectedCandidate
        • BarcodeCandidate
        • PackagedFoodCode
        • AmountEstimate
        • ImagesInfo
        • PassioStatus
        • FoodDetectionEvent
        • NutritionFacts
        • PassioMealPlan
        • PassioMealPlanItem
      • Nutriton Advisor
        • initConversation
        • sendMessage
        • sendImage
        • Guide
          • useNutritionAdvisor
        • Properties
          • PassioAdvisorResponse
          • PassioAdvisorMessageResultStatus
          • PassioAdvisorResultStatus
      • Quick Start Guide
        • Installation
        • Configure the SDK
        • RecognizeImageRemote
        • Food Detail
      • Guide
        • Integrate SDK Setup
        • Integrate Quick Scan
        • Integrate Food Search
        • Integrate Food Editor with Recipe
        • Integrate MealPlan
        • Integrate Suggestions
        • Integrate recognizeImageRemote
      • Components
        • DetectionCameraView
        • PassioIconView
      • Changelog
      • More
        • Display Macro Chart
          • MockFood
          • Utils PassioNutrient
        • Display Micro Progress
        • Getting nutrition value for a FoodItem
        • Getting nutrition value for a Recipe
        • Recalculate the nutrition value based on serving size options.
      • Migrations
        • Migrating from SDK 2.X to version 3.X
        • Structure Migrations From SDK 3.X to SDK 2.X
        • [Deprecated] Migrating from SDK 1.X to version 2.X
        • [Deprecated] Getting Started (v1)
          • Installation
          • SDK Initialization and Configuration
          • Start food detection
          • FoodDetectionEvent
          • Nutritional Database
      • Troubleshooting on RN
      • V2
        • Getting Started
          • Installation
          • SDK Initialization and Configuration
          • Start food detection
          • FoodDetectionEvent
        • RN SDK API
          • Properties
            • PersonalizedAlternative
            • FoodSearchResult
            • PassioNutrient
            • FoodDetectionEvent
            • DownloadModelCallBack
            • UPCProduct
            • ServingUnit
            • PassioStatus
            • PassioIDAttributes
            • PassioIDEntityType
            • PassioFoodItem
            • PassioRecipe
            • ServingSize
            • Measurement
            • UnitMass
            • NutritionFacts
        • Food Image
        • Search Food Item
        • Quick Scan
        • Multi Scan
        • MealPlan
        • Recipe
      • How do I Integrate a Passio SDK in EXPO?
    • Flutter SDK Docs
      • Getting Started
    • Before You Continue
    • Setup For Android
    • Initialize and configure the SDK
  • Fundamentals
    • Nutrition-AI Developer FAQ
      • Nutrition Data
      • Supported Phones
      • Security
      • Testing Volume Estimation
      • Testing Nutrition-AI SDK
      • Nutrition-AI Test Methodology
    • Nutrition API - Mobile SDK interoperability
      • JSON Response parsing
  • Versions
    • 3.2.4
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • 3.2.2
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • 3.2.0
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
    • 3.1.4
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
Powered by GitBook
On this page
  • Install required Libraries
  • Take a Picture
  • Pick Picture from Gallery
  • Let's Recognize the picture using SDK
  • Display the recognition results in the UI
  • Check out the full code here. FULL CODE
Export as PDF
  1. Guides
  2. React Native SDK Docs
  3. Quick Start Guide

RecognizeImageRemote

The RecognizeImageRemote component is responsible for recognizing food items from an image, either by taking a photo using the camera or selecting an image from the gallery. It integrates with the Passio Nutrition SDK to fetch food details and displays the results in a bottom sheet.

Install required Libraries

yarn add react-native-image-picker && expo-camera && @gorhom/bottom-sheet

useCameraPermissions: It seems like you're using a custom hook to handle camera permissions, but it's not a native hook from libraries like expo-camera Ensure that the hook is correctly implemented or imported.

const [permission, requestPermission] = useCameraPermissions();  

useEffect(() => {
    requestPermission();
  }, []);

cameraViewRef: You need to ensure that this ref is properly created and assigned to the camera view. If you're using expo-camera, ensure you're following the right method for capturing images.

  const cameraViewRef = useRef<CameraView>(null);

setPictureUri: This is the state updater function. Whenever a new picture is captured, you'll call setPictureUri with the URI of the picture to update the state. This triggers a re-render of the component with the updated picture URI.

 const [pictureUri, setPictureUri] = useState<string>("");

Take a Picture

  
const takePicture = useCallback(async () => {
    try {
      const picture = await cameraViewRef.current?.takePictureAsync();
      setPictureUri(picture?.uri ?? "");
    } catch (_) {
      Alert.alert("error while capture image");
    }
  }, []);

Pick Picture from Gallery

  const pickImage = useCallback(async () => {
    try {
      const { assets } = await launchImageLibrary({
        mediaType: "photo",
      });
      setPictureUri(assets?.[0].uri ?? "");
    } catch (err) {
      setLoading(false);
    }
  }, []);

Let's Recognize the picture using SDK

The onScanImage function is responsible for sending a captured image to the Passio SDK for remote image recognition . It processes the image, sends it to a remote server for recognition, and updates the local state based on the response.

  const [passioSpeechRecognitionModel, setPassioSpeechRecognitionModel] =
    useState<PassioAdvisorFoodInfo[] | null>();

This part sends the image to PassioSDK for remote recognition.

  • pictureUri?.replace("file://", ""): This removes the file:// prefix from the pictureUri, ensuring it's in a valid format for the SDK to process.

  • The third argument, "RES_512", likely specifies the resolution or processing mode for the image.

import {
  PassioAdvisorFoodInfo,
  PassioSDK,
} from "@passiolife/nutritionai-react-native-sdk-v3";
const onScanImage = () => {
    setPassioSpeechRecognitionModel(null);
    PassioSDK.recognizeImageRemote(
      pictureUri?.replace("file://", "") ?? "",
      undefined,
      "RES_512"
    )
      .then((candidates) => {
        if (candidates?.length === 0){
          Alert.alert("unable to find any food.");
        }else{
          setPassioSpeechRecognitionModel(candidates);
        }
      })
      .catch((e) => {
        Alert.alert("Unable to recognized this image");
      })
      .finally(() => {
        setPictureUri("");
      });
  };

Display the recognition results in the UI

In this UI component using a BottomSheet with dynamic sizing that contains a list of recognized items (from passioSpeechRecognitionModel) and a close button.

          <BottomSheet ref={sheetRef} enableDynamicSizing>
             ...
              <BottomSheetFlatList
                data={passioSpeechRecognitionModel}
                keyExtractor={(_, index) => `${index}`}
                renderItem={renderItem}
                contentContainerStyle={{ paddingTop: 80 }}
                ListFooterComponent={() => <View style={{ height: 50 }} />}
              />              />
          </BottomSheet>

  const renderItem = ({ item }: { item: PassioAdvisorFoodInfo }) => {
    const info = `${item.portionSize} | ${
      item.foodDataInfo?.nutritionPreview?.calories ??
      item?.packagedFoodItem?.ingredients?.[0].referenceNutrients?.calories
        ?.value
    } kcal`;
    const name =
      item?.foodDataInfo?.foodName ??
      item?.packagedFoodItem?.name ??
      item?.recognisedName;
    const iconID = item?.foodDataInfo?.iconID ?? item?.packagedFoodItem?.iconId;

    return (
      <TouchableOpacity
        style={{
          padding: 12,
          flex: 1,
          marginVertical: 4,
          marginHorizontal: 16,
          backgroundColor: "rgba(238, 242, 255, 1)",
          flexDirection: "row",
          borderRadius: 8,
        }}
        onPress={async () => {
         // Pass food detail info
         // Later you can pass food detial on press of item
          if (item.packagedFoodItem) {
            props.onFoodDetail(item.packagedFoodItem);
          } else {
            if (item.foodDataInfo) {
              const dataInfo = await PassioSDK.fetchFoodItemForDataInfo(
                item?.foodDataInfo
              );
              if (dataInfo) {
                props.onFoodDetail(dataInfo);
              }
            }
          }
        }}
      >
        <View
          style={{
            height: 46,
            width: 46,
            borderRadius: 30,
            overflow: "hidden",
          }}
        >
          <PassioIconView
            style={{
              height: 46,
              width: 46,
            }}
            config={{
              passioID: iconID ?? "",
              iconSize: IconSize.PX360,
            }}
          />
        </View>
        <View style={{ flex: 1 }}>
          <Text
            style={[
              {
                flex: 1,
                marginHorizontal: 8,
                fontSize: 16,
              },
              { textTransform: "capitalize" },
            ]}
          >
            {name}
          </Text>
          <Text
            style={{
              flex: 1,
              marginHorizontal: 8,
              fontSize: 16,
            }}
          >
            {info}
          </Text>
        </View>
      </TouchableOpacity>
    );
  };
PreviousConfigure the SDKNextFood Detail

Last updated 7 months ago

Check out the full code here.

FULL CODE