[PYTHON] Combine two images with Django

Overview: A process that combines an image uploaded with Django with a fixed image.

processing:

import json
import numpy as np

import cv2
import os

def upload(request):
    try:
        req_file = request.FILES['image']

        file_path = '/tmp/'

        tmp_dir = file_path
        if not os.path.isdir(tmp_dir):
            os.makedirs(tmp_dir)


        path = os.path.join(tmp_dir, req_file.name)
        destination = open(path, 'wb')

        if req_file.size > 1048576:
            image_data = {
                'status': 400,
                'data': {
                    'message': 'The capacity is over.',
                }
            }
            return JsonResponse(image_data)

        #Write the uploaded image
        for chunk in req_file.chunks():
            destination.write(chunk)

        image = cv2.imread(path)
        width, height = image.shape[:2]


        #Processing to combine with the upper image
        size = width / 10 if width > height else height / 10
        size = int(size)
        margin = size / 5
        margin = int(margin)
        watermark = cv2.imread("Full path of top image", cv2.IMREAD_UNCHANGED)
        watermark = cv2.resize(watermark, (size, size))
        watermark_width, watermark_height = watermark.shape[:2]

        #Extract only the alpha channel of the image
        mask_ = watermark[:,:,3]
        #Create an ndarray that stores the alpha channel value in BGR
        mask = np.ones((watermark_width, watermark_height, 3))
        for i in range(len(mask)):
            for j in range(len(mask[0])):
                mask[i][j] = np.ones(3) * mask_[i][j]
        # 0~Standardized to be 1
        mask = mask / 255.0
        #Cast the value to float.
        image = image.astype('float64')
        #I don't need the alpha channel anymore, so take out the others
        watermark = watermark[:,:,:3]
        #Paste the image in the specified position and return
        image[width - watermark_width -margin:width -margin, height - watermark_height -margin:height -margin] *= 1 - mask
        image[width - watermark_width -margin:width -margin, height - watermark_height -margin:height -margin] += mask * watermark


        root, ext = os.path.splitext(req_file.name)
        file_name = "test" + ext

        #Write a composite image
        cv2.imwrite(tmp_dir + '/' + file_name , image)

        image_data = {
            'status': 200,
            'data': {
                'name': req_file.name,
                'image_url': file_path + "/" + file_name,
                'size': req_file.size
            }
        }
        return JsonResponse(image_data)
    except:
        #Returns 404 if an exception occurs
        traceback.format_exc()
        return Http404("message")

Recommended Posts

Combine two images with Django
Combine FastAPI with Django ORM
Compare two images with image hash
Internationalization with django
CRUD with Django
Authenticate Google with Django
Django 1.11 started with Python3.6
Upload files with Django
Development digest with Django
Output PDF with Django
Markdown output with Django
Use Gentelella with django
Getting Started with Django 1
Send email with Django
File upload with django
Use LESS with Django
Pooling mechanize with Django
Use MySQL with Django
Start today with Django
Center images with python-pptx
Getting Started with Django 2
Automatically download images with scraping
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Bordering images with python Part 1
Get started with Django! ~ Tutorial ⑤ ~
Minimal website environment with django
Create an API with Django
Do Django with CodeStar (Python3.8, Django2.1.15)
Deploy Django serverless with Lambda
Python3 + Django ~ Mac ~ with Apache
Save images with web scraping
Getting Started with Python Django (1)
Create a homepage with django
Getting Started with Python Django (4)
Web application creation with Django
Getting Started with Python Django (3)
Get started with Django! ~ Tutorial ⑥ ~
Save tweet data with Django
Do AES encryption with DJango
Getting Started with Python Django (6)
Getting Started with Django with PyCharm
Real-time web with Django Channels
Double submit suppression with Django
Django REST framework with Vue.js
Use prefetch_related conveniently with Django
Getting Started with Python Django (5)
Login with django rest framework
Qiita API Oauth with Django
Convert PIL format images read from form with Django to base64 format
Test Driven Development with Django Part 3
Number recognition in images with Python
Steps to develop Django with VSCode
Test Driven Development with Django Part 4
Set up social login with Django
Test Driven Development with Django Part 6
Measure Django application coverage with Coverage.py
Handle csv files with Django (django-import-export)
HTTPS with Django and Let's Encrypt
Deploy a Django application with Docker
Common html to rent with Django
Django Model with left outer join