DeepFace analyze function rises serialization issue - python

i would like to use deepface algorithm for detection human's emotion from the image, here is my code :
import cv2
from deepface import DeepFace
import numpy as np
import json
image =cv2.imread('emotion.jpg')
#json.dumps(image)
analyze =DeepFace.analyze(image,actions='emotions',enforce_detection=False)
print(analyze)
but when i have run the code, got the following error
C:\Users\User\PycharmProjects\AI_Project\venv\Scripts\python.exe C:\Users\User\PycharmProjects\AI_Project\emotion_detection.py
Action: e: 0%| | 0/8 [00:00<?, ?it/s]
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\AI_Project\emotion_detection.py", line 7, in <module>
analyze =DeepFace.analyze(image,actions=('emotions'),enforce_detection=False)
File "C:\Users\User\PycharmProjects\AI_Project\venv\lib\site-packages\deepface\DeepFace.py", line 452, in analyze
resp_obj["region"][parameter] = int(region[i]) #int cast is for the exception - object of type 'float32' is not JSON serializable
IndexError: list index out of range
Process finished with exit code 1
i have searched a lot about this problem, for instance try the following code
json.dumps(image)
but when i run, got :
TypeError: Object of type ndarray is not JSON serializable
please tell me is there any solution? or it is just deepface's bug?

you have to pass the image directly. No need to read with opencv & then pass to Deepface.analyze. Read documentaion clearly.
backends = ['opencv', 'ssd', 'dlib', 'mtcnn', 'retinaface', 'mediapipe']
analyze = DeepFace.analyze(img_path = 'emotion.jpg', detector_backend =backends[4])
print(analyze)

Related

Azure Detect With Stream Invalid Request

it's my first time with Azure Face Detection API and I'm using this code right here:
import os
import io
import cv2
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
from PIL import Image, ImageDraw, ImageFont
API_KEY = '...'
ENDPOINT = '...'
image = open('realmadrid.jpg', 'rb')
face_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(API_KEY))
response_detected_faces = face_client.face.detect_with_stream(
image=image,
detection_model='detection_03',
recognition_model='recognition_04',
return_face_landmarks=True,
)
if not response_detected_faces:
raise Exception("No face detected!")
print(f"Number of face detected {len(response_detected_faces)}")
The problem is that everytime I run this code it gives me an exception:
/home/thecowmilk/dev/azure_faceapi/venv/bin/python /home/thecowmilk/dev/azure_faceapi/faceapi/starting.py
Traceback (most recent call last):
File "/home/thecowmilk/dev/azure_faceapi/faceapi/starting.py", line 20, in <module>
detected_faces = face_client.face.detect_with_stream(
File "/home/thecowmilk/dev/azure_faceapi/venv/lib/python3.8/site-packages/azure/cognitiveservices/vision/face/operations/_face_operations.py", line 782, in detect_with_stream
raise models.APIErrorException(self._deserialize, response)
azure.cognitiveservices.vision.face.models._models_py3.APIErrorException: (InvalidRequest) Invalid request has been sent.
Process finished with exit code 1
I don't know how to solve this. It looks there's not much info about Azure Face Detection API. I'd appreciate your thoughts <3!
According to Get face landmarks, to get face landmark data, set the detectionModel parameter to DetectionModel.Detection01 and the returnFaceLandmarks parameter to true.
IList<DetectedFace> faces2 = await faceClient.Face.DetectWithUrlAsync(url: imageUrl, returnFaceId: true, returnFaceLandmarks: true, detectionModel: DetectionModel.Detection01);
Instead of detection_03 use detection_01:
response_detected_faces = face_client.face.detect_with_stream(
image=image,
detection_model='detection_01',
recognition_model='recognition_04',
return_face_landmarks=True,
)
You can refer to recent changes/limitations about some features of Face API: Responsible AI investments and safeguards for facial recognition

Problem with parsing Json from the Supreme-Website in Python

First of all this is my code:
import urllib.request, json
with urllib.request.urlopen("https://www.supremenewyork.com/mobile_stock.json") as url:
data = json.loads(url.read().decode())
print(type(data['Shoes']))
Im trying to parse the Json, that i get from the Supreme Website with Python. Im trying to filter out the 'Shoes' Array. Printing out the whole 'data' works, but if im trying to filter out the 'Shoes' Array, I get this Error:
Traceback (most recent call last):
File "C:\Users\-\PycharmProjects\-\test.py", line 7, in <module>
print(type(data['Shoes']))
KeyError: 'Shoes'
The Json is to long to store it here, but you will find it under:
https://www.supremenewyork.com/mobile_stock.json
print(data['products_and_categories']['Shoes'])
If you look at the json the Shoes are under products and categories:
data["products_and_categories"]["Shoes"]
this will get you the data you need

Getting NameError: name 'video' is not defined in Vapoursynth/Python

Trying to make a gif in vapoursynth, followed tutorials yet keep getting name error. If anyone could help explain what's wrong with it and how to fix it, I would appreciate it.
Failed to initialize script.
Failed to evaluate the script:
Python exception: name 'video' is not defined
Traceback (most recent call last):
File "src\cython\vapoursynth.pyx", line 1927, in
vapoursynth.vpy_evaluateScript
File "src\cython\vapoursynth.pyx", line 1928, in
vapoursynth.vpy_evaluateScript
File "C:/Users/caitl/Pictures/bbh.vpy", line 12, in
core.max_cache_size = 1000 #Use this command to limit the RAM usage. 1000 or 2000 is fine.
NameError: name 'video' is not defined
Code
import os
import vapoursynth as vs
import havsfunc as haf
import mvsfunc as mvs
import descale as descale
import muvsfunc as muvs
import resamplehq as rhq
import CSMOD as cs
import Dither as dither
core = vs.get_core()
video = core.std.Trim(video, a, b)
video = haf.QTGMC(video, Preset="Slower", TFF=True)
video = core.fmtc.resample(video, css="444")
video = descale.Debilinear(video, 629,354)
video = mvs.BM3D(video, sigma=8.84, radius1=1, profile1="fast", matrix="709")
video = hnw.FineSharp(video, sstr=1.13)
video = core.std.CropRel(video, left=72, top=52, right=107, bottom=52)
video = core.fmtc.bitdepth(video, bits=8)
video.set_output()
You didn't define video before the call to Trim which takes it as a parameter.
The example script in the documentation says you need to create a video object, for example, by loading a file:
from vapoursynth import core
video = core.ffms2.Source(source='Rule6.mkv')
This loads a video file Rule6.mkv using the ffms2 plugin, which it assumes is installed correctly.

what is causing "AttributeError: 'numpy.ndarray' object has no attribute 'diff'"

I am new to numpy and I am NOT understanding the documentation as regards diff. the code below throws the error. I am baffled any help would be appreciated.
Traceback (most recent call last):
File "/home/dave/Desktop/mcmtest/testhv calc.py", line 11, in <module>
r = np.log(close_prices).diff()
AttributeError: 'numpy.ndarray' object has no attribute 'diff'
here is the test code.
import numpy as np
from numpy import sqrt,mean,log,diff
import pandas as pd
close_prices = [178.97,175.5,171.07,171.85,172.43,172.99,167.37,164.34,162.71,\
156.41,155.15,159.54,163.03,156.49,160.5,167.78,167.43,166.97,167.96,171.51,171.11]
print (close_prices)
r = np.log(close_prices).diff()
print(r)
Given that numpy.ndarray is the Python type of "numpy arrays", the error is just saying that arrays don't have a diff method. diff is a function defined in the numpy module.
Instead of np.log(close_prices).diff(), do
np.diff(np.log(close_prices))

'Check' object has no attribute 'image' while using sightengine api

I am using sightengine API to detect child sexual abuse in images. In order to do that I am trying to detect the nudity level in an image using sightengine API. The following example is provided in the documentation itself.
from sightengine.client import SightengineClient
client = SightengineClient('api_user', 'api_key')
output = client.check('nudity').image('https://d3m9459r9kwism.cloudfront.net/img/examples/example7.jpg')
Apart from copying the same code I am getting the following error.
Traceback (most recent call last):
File "driver.py", line 3, in <module>
output = client.check('nudity').image('https://d3m9459r9kwism.cloudfront.net/img/examples/example7.jpg')
AttributeError: 'Check' object has no attribute 'image'
I have used both Python 2 and Python 3 for the same code but both raise the same error.
Try This:
from sightengine.client import SightengineClient
client = SightengineClient('API user', 'API secret')
checkNudity = client.check('nudity')
output1 = checkNudity.set_url('https://d3m9459r9kwism.cloudfront.net/img/examples/example7.jpg')
print(output1)

Categories