如何将经过cv2处理的图像保存到Django模型? [英] How do I save a cv2 processed image to django models?
问题描述
我使用opencv裁剪图像,我想将它们保存到模型中,我将文件直接加载到 computeLogoFromMemoryFILE
进行处理,从那里如何将图像保存到 TempImage
模型?
I use opencv to crop images and I'd like to save them to the models, I load the file directly to computeLogoFromMemoryFILE
where it is processed, from there how can I save the image to TempImage
model?
views.py:
form = myForm(request.FILES)
if form.is_valid():
cropped_image = computeLogoFromMemoryFILE(request.FILES.get('logo'))
# ...
temp_image = TempImage.objects.create(image=?)
cv2:
# (np == numpy)
def computeLogoFromMemoryFILE(logo):
logo.seek(0)
image = cv2.imdecode(np.fromstring(logo.read(), np.uint8), cv2.IMREAD_UNCHANGED)
cropped_img = crop_image(image)
cropped_image 变量是一个opencv数组:
cropped_image variable is an opencv array :
array([[ 52, 218, 255],
[ 52, 218, 255],
[ 52, 218, 255],
...,
[ 52, 218, 255],
[ 52, 218, 255],
[ 52, 218, 255]]...], dtype=uint8)
我应该如何进行?
推荐答案
在Django中,每次您需要操作上载的文件,相似的图像并将其设置为Model-Fields时,都必须使用
In Django everytime you needs to manipulate uploaded files, similar images and set these to Model-Fields you must use Django File class, you can doing similar this code:
from django.core.files import File
def my_view(request):
...
form = myForm(request.FILES)
if form.is_valid():
temp_image = myForm.save(commit=False)
cropped_image = computeLogoFromMemoryFILE(request.FILES.get('logo'))
with open('path/of/cropped_image.png', 'rb') as destination_file:
temp_image.image.save('dest.png', File(destination_file), save=False)
temp_image.save()
...
注意:在将文件设置为模型字段之后,此文件克隆到 BytesIO
而不是使用文件存储经过处理的图像.
Note: After setup file to model field this file cloned on the MEDIA_ROOT
, it is better that you remove old image or use BytesIO
instead of using file to store manipulated image.
这篇关于如何将经过cv2处理的图像保存到Django模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!