我使用opencv裁剪图片,并且我想将它们保存到模型中,我将文件直接加载到处理它的computeLogoFromMemoryFILE
,从那里我如何将图像保存到{{ 1}}模型?
views.py:
TempImage
CV2
form = myForm(request.FILES)
if form.is_valid():
cropped_image = computeLogoFromMemoryFILE(request.FILES.get('logo'))
# ...
temp_image = TempImage.objects.create(image=?)
cropped_image 变量是一个opencv数组:
# (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)
我该怎么办?
答案 0 :(得分:2)
在Django中,每次你需要操作上传的文件,类似的图像并将它们设置为Model-Fields,你必须使用Django File类,你可以这样做代码:
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()
...
注意:将文件设置为模型字段后,此文件克隆在MEDIA_ROOT
上,最好删除旧图像或使用BytesIO
而不是使用文件存储操纵图像。
答案 1 :(得分:0)
型号:
class ImageModel(models.Model):
image = models.FileField(upload_to='images/')
查看:
from django.core.files.base import ContentFile
def index(request):
...
ret, buf = cv2.imencode('.jpg', cropped_image) # cropped_image: cv2 / np array
content = ContentFile(buf.tobytes())
img_model = ImageModel()
img_model.image.save('output.jpg', content)
ContentFile支持的字节和字符串:https://docs.djangoproject.com/en/3.1/ref/files/file/#django.core.files.base.ContentFile