i have a problem with my code, it is object detection app, when i run it camera loads okay but i get some Promise Errors:
[Unhandled promise rejection: TypeError: Cannot read property ‘ready’ of undefined]
[Unhandled promise rejection: Error: Backend ‘undefined’ has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods]
this is my code:
const { width, height } = Dimensions.get("window");
const TensorCamera = cameraWithTensors(Camera);
function App() {
const [model, setModel] = useState(null);
const context = useRef();
const camera = useRef();
useEffect(() => {
(async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
if (status !== "granted") {
alert("not granted");
return;
}
await tf.ready();
const loadedModel = await cocoSsd.load();
setModel(loadedModel);
})();
}, []);
useEffect(() => {
(async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
if (status !== "granted") {
alert("Разрешение на использование камеры не предоставлено.");
}
})();
}, []);
const handleCameraStream = (images) => {
const loop = async () => {
const nextImageTensor = images.next().value;
if (!model || !nextImageTensor) return;
const predictions = await model.detect(nextImageTensor);
drawRectangles(predictions);
requestAnimationFrame(loop);
};
loop();
};
const drawRectangles = (predictions) => {
if (!context.current || !camera.current) return;
const scaleWidth = width / camera.current.width;
const scaleHeight = height / camera.current.height;
context.current.clearRect(0, 0, width, height);
for (const prediction of predictions) {
const [x, y, width, height] = prediction.bbox;
const boundingBoxX = x * scaleWidth;
const boundingBoxY = y * scaleHeight;
context.current.strokeRect(
boundingBoxX,
boundingBoxY,
width * scaleWidth,
height * scaleHeight
);
context.current.fillText(
`${prediction.class} (${Math.round(prediction.score * 100)}%)`,
boundingBoxX,
boundingBoxY > 10 ? boundingBoxY - 5 : 10
);
}
};
const handleCanvas = (can) => {
if (can) {
can.width = width;
can.height = height;
const ctx = can.getContext("2d");
context.current = ctx;
ctx.strokeStyle = "red";
ctx.fillStyle = "red";
ctx.lineWidth = 2;
camera.current = can;
}
};
return (
<View style={styles.container}>
<TensorCamera
style={styles.camera}
type={Camera.Constants.Type.back}
cameraTextureWidth={width}
cameraTextureHeight={height}
resizeWidth={width}
resizeHeight={height}
resizeDepth={3}
onReady={handleCameraStream}
autorender={true}
useCustomShadersToResize={false}
/>
<View style={styles.canvasContainer}>
<Text style={styles.instructions}>Detected Objects:</Text>
<Canvas style={styles.canvas} ref={handleCanvas} />
</View>
</View>
);
}