Python 将文件字段编码和解码为字节
我的目标是将文件对象(用户上传的视频)更改为字节,然后将其分块,然后再次将这些分块更改为图像或帧。以下代码是django应用程序的一个片段Python 将文件字段编码和解码为字节,python,django,byte,Python,Django,Byte,我的目标是将文件对象(用户上传的视频)更改为字节,然后将其分块,然后再次将这些分块更改为图像或帧。以下代码是django应用程序的一个片段 def handle_uploaded_file(f): with open('./chunks_made.txt', 'wb+') as destination: for chunk in f.chunks(): print(type(chunk)) print(len(chunk))
def handle_uploaded_file(f):
with open('./chunks_made.txt', 'wb+') as destination:
for chunk in f.chunks():
print(type(chunk))
print(len(chunk))
destination.write(chunk)
chunk_length = len(chunk)
read_batches(len(chunk))
def read_batches(chunk_size):
with open('./chunks_made.txt', 'rb') as file:
content = file.read(chunk_size)
frame = cv2.imdecode(content, cv2.IMREAD_COLOR)
plt.imshow(frame)
plt.show()
调用这些函数的流程视图:
def process(request):
video_file = request.FILES['video']
handle_uploaded_file(video_file)
data = 'some_data'
return render(request, 'video/result.html', {'data':video_file})
我不知道如何将字节解码成帧作为真实图像。
cv2.imdecode()
为您提供numpy.array
和image
,但您必须使用return
将其发送回进程。如果您希望它是PNG
或JPG
,则必须将numpy.array
转换为文件数据,即cv2.imencode(frame,.PNG”)
。若你们希望它显示在浏览器中,那个么你们可以将它保存在文件中,并将ulr发送到这个文件中。或者您可以将其转换为base64
并使用
今天的问题与此类似,但在Flask
中,我不知道您想做什么。我不知道你是什么意思,如果你指的是原始数据(逐像素),你可以改变(调整大小,旋转,在机器学习中使用),那么你就有了单帧frame=cv2.imdecode(…)
。如果您指的是MOV/MP4/AVI视频,那么您可以将其保存在文件/chunks\u made.txt
中。如果您的意思是将单个帧作为PNG/JPG图像(您可以将其发送到浏览器以显示),则必须使用cv2.imencode(frame,.PNG”)