React-Native Face detect from list of images - javascript

i want to detect faces from list of images which are listed from photo albums..
here is my code..
// get All images from particular album
await CameraRoll.getPhotos({
first: count,
after,
assetType: 'Photos',
groupTypes: 'All',
groupName: this.props.navigation.state.params.album,
})
.then(r => {
this.setState({ data: r.edges, isLoading: false, });
this.state.data.map((p, index) => {
this.getFaces(p.node.image.uri);
});
})
}
// Detect faces from list of images
async getFaces(uri) {
await FaceDetector.detectFacesAsync(uri).then(res => {
if (res.faces.length > 0) {
console.log('Has faces: ' + uri);
this.state.faceImage.push(uri); // array of face images and set it to Flatlist
} else {
console.log('No faces: ' + uri);
}
});
this.setState({
faceImage: this.state.faceImage,
isLoading: false,
});
}
All things are worked correctly but when image array size was big then my app was stuck and close only in android device.

Try to split it to new array when the size of the array is to big

Have you tried to save it to file and load it from there?

Related

Crop image to variable in react

I'm creating an app that detects faces and classifies faces' ethnicity using 2 Clarifai APIs. The issue is ethnicity classifier can only do 1 face for 1 photo. My solution is cropping the faces by face detection and then separately classify each face's ethnicity.
Then I got stuck with an idea: I want to crop the face by the coordination provided by the face detection and save the faces to variables, so I can use ethnicity classifier for each face.
I would love to receive some help from you guys. Thank you.
Here is the code of my issue
this.setState({imageURL: this.state.input});
app1.models
.predict(
{
id: 'ethnicity-demographics-recognition',
name: 'appearance-multicultural',
version: 'b2897edbda314615856039fb0c489796',
type: 'visual-classifier',
},
this.state.input
)
.then((response) => console.log('ethnic',response))
.catch((err) => {
console.log("Clarifai Error:", err);
});
app2.models
.predict(
{
id: 'face-detection',
name: 'face-detection',
version: '6dc7e46bc9124c5c8824be4822abe105',
type: 'visual-detector',
}, this.state.input)
.then((response) => {
const regions = response.outputs[0].data.regions;
const box = [];
regions.forEach(region => {
box.push(this.calculateFaceLocation(region))
});
this.displayFaceBox(box);
})
.catch((err) => {
console.log("Clarifai Error:", err);
});
I looked up some solution like HTML canvas and react-image-crop, but I am still unable to save the faces as variables.

woocommerce store api + reactjs - add to cart not working

I have a react app Im working on to create a new frontend for an already live woocommerce site. I'm using this endpoint /wp-json/wc/store/v1/cart/add-item like so -
let config = {
method: "post",
url: "http://localhost:8010/proxy/wp-json/wc/store/v1/cart/add-item",
data: {
id : id,
quantity: 1,
variation: [
{
attribute: "Color",
value: color,
},
{
attribute: "Size",
value: size,
}
]
}
}
console.log(config)
const resp = await axios(config).then((response) => {
console.log(response.data)
})
.catch((error) => {
console.log(error.response.data);
});
Which is giving me a successful json response showing I have the item added -
items_count: 1
Then I have a cart component to api call and render -
useEffect(() => {
getCart();
}, []);
const getCart = async () => {
let config = {
method: "get",
url: "http://localhost:8010/proxy/wp-json/wc/store/v1/cart"
}
await axios(config).then((response) => {
console.log(response.data)
})
.catch((error) => {
console.log(error.response.data);
});
}
However when navigating to this page/component or any other, the api call is returning an empty cart - items_count: 0
On the checkout page I tried using a different endpoint wp-json/wc/store/v1/checkout but this is giving me an error -
code: "woocommerce_rest_cart_empty" data: {status: 400} message: "Cannot create order from empty cart."
Any ideas why this is happening?
It's possible that the request isn't setting a cookie which will prevent the cart from working as expected. In my experience, I can make a build of my React app and activate it as a WordPress theme. Then the add-to-cart works as expected. But if I'm using the live preview of the app instead, the add-to-cart will not work because the cookie is missing. Here's a GitHub issue about it.
https://github.com/woocommerce/woocommerce-blocks/issues/5683

my image doesn't display on screen when i try to get it from api

i am trying to get an image from api and display it to screen i recieve the addrees and set it to state
when i log the state it is null
this is my code
useEffect(() => {
baseUrl
.get(`/api/v1/questions/${id}/edit`)
.then((response) => {
setLoading(false);
const data = response.data.data.data;
console.log(data);
setImageUrlQuestion(`https://panel.farostaha.com${data.question}`);
console.log(`https://panel.farostaha.com${data.question}`);
console.log(imageUrlQuestion);
setImageUrlAnswer(`https://panel.farostaha.com${data.answer}`);
setSelectedBookOption({ value: data.book.id, label: data.book.name });
setSelectedSubjectOption({
value: data.subject.id,
label: data.subject.name,
});
other parts works correctly but the images in the state are null

React | Facebook JS API : Error code 100 when trying to upload multiple images to my page feed

In a first function, I upload multiple images to page-id/photos and receive a positive response with all the ids of these images.
The next part however is where I'm stuck; I am now trying to create a post with multiple images to my Facebook page timeline. However, I'm getting a weird error response claiming that I already have uploaded my images.
I've even followed Facebook's own example from their documentation using Open Graph Explorer, but that just returns another error
Function to send image:
(works without a problem)
sendFacebookImagePost(page) {
const attached_media = []
for(let i = 0; i < this.state.upload_imgsrc.length; i++) {
let reader = new FileReader();
reader.onload = (e) => {
let arrayBuffer = e.target.result;
let blob = new Blob([arrayBuffer], { type: this.state.upload_imgsrc[i].type });
let data = new FormData()
data.append("source", blob)
data.append("message", this.state.fb_message)
data.append("no_story", true)
data.append("published", true)
axios({
method: "post",
url: "https://graph.facebook.com/" + page.id + "/photos?access_token=" + page.accessToken,
data: data
})
.then(response => {
attached_media.push({media_fbid: response.data.id})
if (attached_media.length === this.state.upload_imgsrc.length) {
this.sendFacebookPost(page, attached_media)
}
})
.catch(error => {
console.log(error);
})
}
reader.readAsArrayBuffer(this.state.upload_imgsrc[i]);
}
}
Function to send post:
(Here is where the error happens)
sendFacebookPost(page, attached_media) {
let data = {
message: this.state.fb_message,
link: this.state.fb_link,
attached_media: attached_media
// this is what attached_media returns:
// [
// {media_fbid: response.data.id},
// {media_fbid: response.data.id}
// ]
}
axios({
method: "post",
url: "https://graph.facebook.com/" + page.id + "/feed?access_token=" + page.accessToken,
data: data
})
.then( () => this.setState({fb_successMessage: "Post successful!", fb_errorMessage: ""}) )
.catch(error => {
console.log(error);
})
}
Error code
error: {
code: 100
error_subcode: 1366051
error_user_msg: "These photos were already posted."
error_user_title: "Already Posted"
fbtrace_id: "Cl9TUTntOZK"
is_transient: false
message: "Invalid parameter"
type: "OAuthException"
}
My try on Open Graph Explorer
Problem solved.
The part that went wrong is where I add the following to my image post:
data.append("published", true). Apparently, images you want to use in a multi photo post have to be set to published: false before they can be used in a post. Otherwise, Facebook sees this as already uploaded.

Firebase Storage | Angular 2 - Proper way to display image after upload

When creating an event, I also upload an image to Firebase Storage.
Then I create an array this.eventz to display the events on the home page. For each event I want to retrieve the image as well, but I get a Firebse error:
FirebaseStorageError {code_: "storage/object-not-found", message_: "Firebase Storage: Object 'events/-KxCuUuss1I2uFolk99m/-KxCuUuss1I2uFolk99m_main.png' does not exist.", serverResponse_: "{↵ "error": {↵ "code": 404,↵ "message": "Not Found. Could not get object"↵ }↵}", name_: "FirebaseError"}
I understand that the image isn't uploaded yet when I want to include it in the array but I don't know how to fix my problem. The code works fine. It displays all the events, adds images to each one ... it's just that error when creating a new event.
getEventImage(event) {
if (event) {
const mainPhotoRef = firebase.storage().ref('events');
console.log(mainPhotoRef);
mainPhotoRef.child(`/${event.key}/${event.key}_main.png`).getDownloadURL()
.then(url => this.makeEvents(url, event))
}
}
makeEvents(url, event) {
console.log(url);
if (url) {
try {
event.img = url;
let index = _.findIndex(this.eventz, ['key', event.key]);
if (index >= 0) {
this.eventz.splice(index, 1);
}
this.eventz.push(event);
} catch (err) {
console.log(err);
}
}
}
I fixed my problem by saving the url to the event object when creating it. I would like to know if I am uploading correctly.
private uploadPhoto(itemKey): void {
this.myPhotosRef.child(itemKey).child(`${itemKey}_main.png`)
.putString(this.myPhoto, 'base64', { contentType: 'image/png' })
.then((savedPicture) => this.updateEventImage(savedPicture.downloadURL, itemKey));
}
updateEventImage(url, itemKey) {
console.log(url);
const newEvent = this.db.object(`events/${itemKey}`)
newEvent.update({ eventImage: url });
}

Categories

Resources