Я пытаюсь построить нативное приложение React с Expo и застрял здесь
iam застрял с этой строкой
"import {вывод, тензор} от 'onncruntime-regact-cnative';" Когда я удалил эту строку и изменил код (удалили эти используемые функции: {выводы, тензор} < /strong>), я не получаю никаких ошибок. Но я хочу, чтобы onnxruntime-react-cnity это было использовано. p>
Я разрабатываю нативное приложение React с использованием Expo, где я стремлюсь интегрировать модель ONNX для распознавания лица. Приложение позволяет пользователям выбирать изображение, предварительно обрабатывать его и выполнять вывод, используя время выполнения ONNX для RACE Native. Тем не менее, я сталкиваюсь с несколькими проблемами во время разработки:
Вот выход, который я вижу в приложении:
Вот код, который я написал в index.jsx ~ Я заменил index.tsx на jsx :
import React, { useState } from 'react';
import { View, Button, Image, Text, StyleSheet, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { InferenceSession, Tensor } from 'onnxruntime-react-native';
import * as FileSystem from 'expo-file-system';
export default function App () {
const [imageUri, setImageUri] = useState(null);
const [output, setOutput] = useState(null);
// Load the ONNX model
const loadModel = async () => {
try {
const modelPath =
Platform.OS === 'android'
? `file:///android_asset/face_encoder.onnx` // Android path for assets
: `${FileSystem.documentDirectory}face_encoder.onnx`; // iOS path
// Load the ONNX model
const session = await InferenceSession.create(modelPath);
return session;
} catch (error) {
console.error('Error loading model:', error);
}
};
// Process image and run inference
const processImage = async (session) => {
if (!imageUri) return;
try {
// Convert image to tensor (mocked for simplicity)
// In practice, preprocess the image (resize to 224x224, normalize, etc.)
const inputTensor = new Float32Array(3 * 224 * 224).fill(0.5);
const tensor = new Tensor('float32', inputTensor, [1, 3, 224, 224]);
// Run inference
const feeds = { input: tensor };
const results = await session.run(feeds);
// Process results
setOutput(results.output.data);
} catch (error) {
console.error('Error processing image:', error);
}
};
const handleLoadImage = async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.canceled) {
setImageUri(result.uri);
}
};
const handleRunModel = async () => {
const session = await loadModel();
if (session) {
await processImage(session);
}
};
return (
Face Recognition App
{imageUri && }
{output && Output: {JSON.stringify(output)}}
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
image: {
width: 200,
height: 200,
marginVertical: 20,
},
});
вот app.json :
{
"expo": {
"name": "FceDetectionApp",
"slug": "FceDetectionApp",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "myapp",
"userInterfaceStyle": "automatic",
"newArchEnabled": true,
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/images/adaptive-icon.png",
"backgroundColor": "#ffffff"
},
"package": "Face.Files"
},
"web": {
"bundler": "metro",
"output": "static",
"favicon": "./assets/images/favicon.png"
},
"plugins": [
"expo-router",
[
"expo-splash-screen",
{
"image": "./assets/images/splash-icon.png",
"imageWidth": 200,
"resizeMode": "contain",
"backgroundColor": "#ffffff"
}
]
],
"experiments": {
"typedRoutes": true
},
"extra": {
"router": {
"origin": false
},
"eas": {
"projectId": "81f38c43-7dd5-4bfc-ad5d-fbb101bd1d3a"
}
}
}
}
< /code>
package.json Зависимости: < /p>
"dependencies": {
"@expo/vector-icons": "^14.0.2",
"@react-navigation/bottom-tabs": "^7.2.0",
"@react-navigation/native": "^7.0.14",
"expo": "~52.0.23",
"expo-blur": "~14.0.1",
"expo-constants": "~17.0.3",
"expo-font": "~13.0.2",
"expo-haptics": "~14.0.0",
"expo-image-picker": "^16.0.3",
"expo-linking": "~7.0.3",
"expo-router": "~4.0.15",
"expo-splash-screen": "~0.29.18",
"expo-status-bar": "~2.0.0",
"expo-symbols": "~0.2.0",
"expo-system-ui": "~4.0.6",
"expo-web-browser": "~14.0.1",
"onnxruntime-react-native": "^1.20.1",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-native": "0.76.5",
"react-native-gesture-handler": "~2.20.2",
"react-native-get-random-values": "~1.11.0",
"react-native-reanimated": "~3.16.1",
"react-native-safe-area-context": "4.12.0",
"react-native-screens": "~4.4.0",
"react-native-web": "~0.19.13",
"react-native-webview": "13.12.5"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@types/jest": "^29.5.12",
"@types/react": "~18.3.12",
"@types/react-test-renderer": "^18.3.0",
"jest": "^29.2.1",
"jest-expo": "~52.0.2",
"react-test-renderer": "18.3.1",
"typescript": "^5.3.3"
},
Подробнее здесь: https://stackoverflow.com/questions/793 ... mponent-st
(Nobridge) Typeerror: не удается прочитать свойство «Установка» из NULL [Стек компонентов] ⇐ Android
Форум для тех, кто программирует под Android
1739847595
Anonymous
Я пытаюсь построить нативное приложение React с Expo и застрял здесь
iam застрял с этой строкой
[b] "import {вывод, тензор} от 'onncruntime-regact-cnative';" [/b] Когда я удалил эту строку и изменил код (удалили эти используемые функции: [b] {выводы, тензор} < /strong>), я не получаю никаких ошибок. Но я хочу, чтобы onnxruntime-react-cnity [/b] это было использовано. p>
Я разрабатываю нативное приложение React с использованием Expo, где я стремлюсь интегрировать модель ONNX для распознавания лица. Приложение позволяет пользователям выбирать изображение, предварительно обрабатывать его и выполнять вывод, используя время выполнения ONNX для RACE Native. Тем не менее, я сталкиваюсь с несколькими проблемами во время разработки:
Вот выход, который я вижу в приложении:
Вот код, который я написал в [b] index.jsx [/b] ~ Я заменил [b] index.tsx [/b] на [b] jsx [/b]:
import React, { useState } from 'react';
import { View, Button, Image, Text, StyleSheet, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { InferenceSession, Tensor } from 'onnxruntime-react-native';
import * as FileSystem from 'expo-file-system';
export default function App () {
const [imageUri, setImageUri] = useState(null);
const [output, setOutput] = useState(null);
// Load the ONNX model
const loadModel = async () => {
try {
const modelPath =
Platform.OS === 'android'
? `file:///android_asset/face_encoder.onnx` // Android path for assets
: `${FileSystem.documentDirectory}face_encoder.onnx`; // iOS path
// Load the ONNX model
const session = await InferenceSession.create(modelPath);
return session;
} catch (error) {
console.error('Error loading model:', error);
}
};
// Process image and run inference
const processImage = async (session) => {
if (!imageUri) return;
try {
// Convert image to tensor (mocked for simplicity)
// In practice, preprocess the image (resize to 224x224, normalize, etc.)
const inputTensor = new Float32Array(3 * 224 * 224).fill(0.5);
const tensor = new Tensor('float32', inputTensor, [1, 3, 224, 224]);
// Run inference
const feeds = { input: tensor };
const results = await session.run(feeds);
// Process results
setOutput(results.output.data);
} catch (error) {
console.error('Error processing image:', error);
}
};
const handleLoadImage = async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.canceled) {
setImageUri(result.uri);
}
};
const handleRunModel = async () => {
const session = await loadModel();
if (session) {
await processImage(session);
}
};
return (
Face Recognition App
{imageUri && }
{output && Output: {JSON.stringify(output)}}
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
image: {
width: 200,
height: 200,
marginVertical: 20,
},
});
вот [b] app.json [/b]:
{
"expo": {
"name": "FceDetectionApp",
"slug": "FceDetectionApp",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "myapp",
"userInterfaceStyle": "automatic",
"newArchEnabled": true,
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/images/adaptive-icon.png",
"backgroundColor": "#ffffff"
},
"package": "Face.Files"
},
"web": {
"bundler": "metro",
"output": "static",
"favicon": "./assets/images/favicon.png"
},
"plugins": [
"expo-router",
[
"expo-splash-screen",
{
"image": "./assets/images/splash-icon.png",
"imageWidth": 200,
"resizeMode": "contain",
"backgroundColor": "#ffffff"
}
]
],
"experiments": {
"typedRoutes": true
},
"extra": {
"router": {
"origin": false
},
"eas": {
"projectId": "81f38c43-7dd5-4bfc-ad5d-fbb101bd1d3a"
}
}
}
}
< /code>
package.json Зависимости: < /p>
"dependencies": {
"@expo/vector-icons": "^14.0.2",
"@react-navigation/bottom-tabs": "^7.2.0",
"@react-navigation/native": "^7.0.14",
"expo": "~52.0.23",
"expo-blur": "~14.0.1",
"expo-constants": "~17.0.3",
"expo-font": "~13.0.2",
"expo-haptics": "~14.0.0",
"expo-image-picker": "^16.0.3",
"expo-linking": "~7.0.3",
"expo-router": "~4.0.15",
"expo-splash-screen": "~0.29.18",
"expo-status-bar": "~2.0.0",
"expo-symbols": "~0.2.0",
"expo-system-ui": "~4.0.6",
"expo-web-browser": "~14.0.1",
"onnxruntime-react-native": "^1.20.1",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-native": "0.76.5",
"react-native-gesture-handler": "~2.20.2",
"react-native-get-random-values": "~1.11.0",
"react-native-reanimated": "~3.16.1",
"react-native-safe-area-context": "4.12.0",
"react-native-screens": "~4.4.0",
"react-native-web": "~0.19.13",
"react-native-webview": "13.12.5"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@types/jest": "^29.5.12",
"@types/react": "~18.3.12",
"@types/react-test-renderer": "^18.3.0",
"jest": "^29.2.1",
"jest-expo": "~52.0.2",
"react-test-renderer": "18.3.1",
"typescript": "^5.3.3"
},
Подробнее здесь: [url]https://stackoverflow.com/questions/79330700/nobridge-error-typeerror-cannot-read-property-install-of-null-component-st[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия