如何在不保存图像的情况下将

如何在不保存图像的情况下将

本文介绍了如何在不保存图像的情况下将 Numpy 数组图像转换为 JPEG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Microsoft Azure 的人脸 API 来检测视频中人物的情绪.我有一个 Python 程序可以正确处理本地图像,现在我正在尝试拍摄本地视频并将每一帧发送到 API,并存储每次分析的结果.

I'm using Microsoft Azure's Face API to detect the emotions of a person in a video. I have a Python program working correctly with local images, and now I'm trying to take a local video and send each frame to the API, and store the result of each analysis.

发送到 Azure 的人脸 API 的数据需要是一个以字节形式读取的 PNG/JPG 文件:

The data sent to Azure's Face API needs to be a PNG/JPG file read as bytes:

image_data=open(image_source, "rb").read()

OpenCV 似乎是使用 Python 逐帧浏览视频的标准,但这些帧属于 Numpy 数组类型.您可以拍摄视频的每一帧并将其以 JPG 格式保存到磁盘,如下所示:

OpenCV seems to be the standard for going frame by frame through a video with Python, but the frames are of the type Numpy array. You can take each frame of a video and save it as a JPG to disk like so:

import cv2 # OpenCV
vidcap = cv2.VideoCapture('vid.mp4')
success, image = vidcap.read()
count = 1
while success:
  cv2.imwrite("video_data/frame_%d.jpg" % count, image)
  success, frame = vidcap.read() # frame is a Numpy array
  print('Saved frame ', count)
  count += 1

但这不是我想要的.有没有办法在不将文件保存到磁盘的情况下将这个 Numpy 数组转换为 JPG?我只想将其转换为 JPG,然后将该图像作为字节发送到 Azure API.

But this isn't exactly what I want. Is there anyway to do this Numpy array to JPG conversion without saving a file to disk? I just want to convert it to JPG, then send that image as bytes to the Azure API.

感谢所有建议和指导,谢谢!

Any and all advice and guidance is appreciated, thanks!

通过将 Numpy 数组框架转换为 PIL Image 对象并通过 BytesIO 库模块将其转换为 PNG,我有一个可行的解决方法.如果有人有任何更有效/更好/更清洁/更好的解决方案,我仍然很想听听他们的意见!

I've got a working work-around by converting the Numpy array frame to a PIL Image object and converting it to a PNG through the BytesIO library module. If anyone has any more efficient/nicer/cleaner/better solutions, I would still love to hear them!

推荐答案

你只需要 cv2.imencode() 像这样:

success, frame = vidcap.read()
_, JPEG = cv2.imencode('.jpeg', frame)

JPEG 现在将是一个包含 JPEG 编码图像的 Numpy 数组.如果要将其作为字节发送到 Azure,可以发送:

JPEG will now be a Numpy array containing a JPEG-encoded image. If you want to send it to Azure as bytes, you can send:

JPEG.tobytes()

这篇关于如何在不保存图像的情况下将 Numpy 数组图像转换为 JPEG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 20:56