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