- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个项目,我想在其中执行实时面部情绪识别。
一个客户打开一个网页,他的面部图像被一个摄像头(内置笔记本电脑摄像头)捕获,然后这个视频被绘制在 Canvas (HTML 元素)上,然后转换成 BLOB 并通过 Python 发送Websocket 到 Python 服务器后端。在那里 - 我需要使用另一个 Python 脚本(将图像作为输入)执行情感分析 - 所以我需要将这个 BLOB 转换回图像,但我不知道如何正确地进行,我一个接一个地收到错误,因为我是 Python 的新手,所以我不知道如何解决这个任务。
到目前为止,我设法打开了 websocket,实时发送了这个 BLOB,但随后发生了一些神奇的事情,一切都崩溃了——可能我将函数放入循环的方式以及我转换图像的方式也有问题数据。
HTML 片段:
<div class="booth">
<video id="video" width="320" height="240"></video>
<canvas width="320" id="canvas" height="240" style="display: inline;"></canvas>
</div>
<script src="canvas.js"></script>
Canvas .js:
(function () {
var video = document.getElementsByTagName("video")[0];
var canvas = document.getElementsByTagName("canvas");
var ctx = canvas[0].getContext('2d');
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true,
audio: false,
}, function (stream) {
console.log("I'm in live function")
console.log(stream);
video.srcObject = stream;
video.play();
}, function (error) {
console.log("Error in live" + error)
error.code
});
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: mimeString });
}
var ws = new WebSocket(" ws://127.0.0.1:5678/");
ws.onopen = function () {
console.log("Openened connection to websocket");
}
timer = setInterval(
function () {
ctx.drawImage(video, 0, 0, 320, 240);
var data = canvas[0].toDataURL('image/jpeg', 1.0);
newblob = dataURItoBlob(data);
ws.send(newblob);
}, 100);
})();
web_socket_server.py :
async def time(websocket, path):
detection_model_path = r'C:\Users\karol\face_recognition\haarcascade_frontalface_default.xml'
emotion_model_path = r'C:\Users\karol\face_recognition\models_mini_XCEPTION.88-0.65.hdf5'
face_detection = cv2.CascadeClassifier(detection_model_path)
emotion_classifier = load_model(emotion_model_path, compile=False)
EMOTIONS = ["angry", "disgust", "scared", "happy", "sad", "surprised",
"neutral"]
# starting video streaming
while True:
message = await websocket.recv()
print(f"We got message from the client!")
print (message)
#images = message.decode('base64')
#message = base64.encodebytes(message)
#print(message)
face_rec.emotion_detection(message, face_detection, emotion_classifier, EMOTIONS)
start_server = websockets.serve(time, "127.0.0.1", 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
人脸记录.py:
def decode_base64(data, altchars=b'+/'):
data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data) # normalize
missing_padding = len(data) % 4
if missing_padding:
data += b'='* (4 - missing_padding)
return base64.b64decode(data, altchars)
def stringToRGB(base64_string):
imgdata = decode_base64(base64_string)
image = Image.open(io.BytesIO(imgdata)) //HERE I GET THE ERROR "cannot identify image file %r(filename if filename else fp))"
return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
def emotion_detection(bytes, face_detection, emotion_classifier, EMOTIONS):
while True:
image = stringToRGB(bytes)
frame = imutils.resize(image, width=400)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
canvas = np.zeros((250, 300, 3), dtype="uint8")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse=True,
key=lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 48x48 pixels, and then prepare
# the ROI for classification via the CNN
roi = gray[fY:fY + fH, fX:fX + fW]
roi = cv2.resize(roi, (48, 48))
roi = roi.astype("float") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis=0)
preds = emotion_classifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = "{}: {:.2f}%".format(emotion, prob * 100)
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)
cv2.imshow('your_face', frameClone)
cv2.imshow("Probabilities", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#camera.release()
cv2.destroyAllWindows()
我知道代码很多,但我想更广泛地说明我想做什么。拜托,如果有人能给我提示我应该如何正确处理这种转变,请告诉我 ;)
最佳答案
我得到了一些有用的东西,这可能对你有帮助(它将二进制数据从 javascript websocket 发送到 python 服务器,并将接收到的数据转换为你似乎在使用的枕头库的图像)。试试这个作为客户端站点脚本:
(async () => {
const useFrameRate = 30;
const stream = await navigator.mediaDevices.getUserMedia({video: true});
const capture = new ImageCapture(stream.getVideoTracks()[0]);
const socket = new WebSocket('ws://localhost:5678');
const options = {imageWidth: 640, imageHeight: 480};
socket.addEventListener('open', () => {
const send = () => capture.takePhoto(options).then(blob => socket.send(blob)).catch(() => {});
const sendloop = setInterval(send ,1000/useFrameRate);
});
})();
然后在你的服务器上是这样的:
import asyncio
import websockets
import io
from PIL import Image, ImageMode
async def time(websocket, path):
while True:
message = await websocket.recv()
image = Image.open(io.BytesIO(message))
# now do with your images whatever you want. I used image.show to check it, it was spamming my monitor
start_server = websockets.serve(time, "127.0.0.1", 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
解释:
起初,我想绕过 canvas 方法,直接从 getUserMedia-Stream 中抓取一个 Blob。我为此使用了 ImageCapture-API,尤其是 takePhoto(),它返回一个 Blob。
如果你愿意,你可以保留你的 Canvas 方法并调用.toBlob()。在你的 Canvas 上。
标准的 websocket 不仅接受字符串,还接受像 Blob 这样的字节对象,参见 here .它会自动将它们转换为二进制帧,您可以在 python 中将其作为二进制字符串处理,因为您已经正确地尝试过 io.BytesIO。
关于python - 使用 WebRTC 和 Python 服务器进行人脸情绪分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58457069/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!