How do I save a cv2 processed image to django models?

こ雲淡風輕ζ 提交于 2020-12-10 12:14:04

问题


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 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)

How should I proceed?


回答1:


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()
    ...

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.




回答2:


Model:

class ImageModel(models.Model):
    image = models.FileField(upload_to='images/')

View:

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 support bytes and string: https://docs.djangoproject.com/en/3.1/ref/files/file/#django.core.files.base.ContentFile



来源:https://stackoverflow.com/questions/49170964/how-do-i-save-a-cv2-processed-image-to-django-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!