Published: Jan. 21, 2021 by lukemakin |  estimated reading time: 7 minutes
django opencv integration python
 
Source code to the youtube tutorial on how to integrate django with opencv.

The purpose of this video is to show how to integrate django web framework with computer vision library


To follow along you will need Anaconda. You can get it over here:
https://www.anaconda.com/products/individual




models.py

from django.db import models
from .utils import get_filtered_image
from PIL import Image
import numpy as np
from io import BytesIO
from django.core.files.base import ContentFile

# Create your models here.
ACTION_CHOICES= (
('NO_FILTER', 'no filter'),
('COLORIZED', 'colorized'),
('GRAYSCALE', 'grayscale'),
('BLURRED', 'blurred'),
('BINARY', 'binary'),
('INVERT', 'invert'),
)

class Upload(models.Model):
image = models.ImageField(upload_to='images')
action = models.CharField(max_length=50, choices=ACTION_CHOICES)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)

def __str__(self):
return str(self.id)

def save(self, *args, **kwargs):

# open image
pil_img = Image.open(self.image)

# convert the image to array and do some processing
cv_img = np.array(pil_img)
img = get_filtered_image(cv_img, self.action)

# convert back to pil image
im_pil = Image.fromarray(img)

# save
buffer = BytesIO()
im_pil.save(buffer, format='png')
image_png = buffer.getvalue()

self.image.save(str(self.image), ContentFile(image_png), save=False)

super().save(*args, **kwargs)

admin.py


from django.contrib import admin
from .models import Upload
# Register your models here.

admin.site.register(Upload)

utils.py


import cv2

def get_filtered_image(image, action):
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
filtered = None
if action == 'NO_FILTER':
filtered = image
elif action == 'COLORIZED':
filtered = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
elif action == 'GRAYSCALE':
filtered = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
elif action == 'BLURRED':
width, height = img.shape[:2]
if width > 500:
k = (50, 50)
elif width > 200 and width <=500:
k = (25,25)
else:
k = (10,10)
blur = cv2.blur(img, k)
filtered = cv2.cvtColor(blur, cv2.COLOR_BGR2RGB)
elif action == 'BINARY':
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, filtered = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
elif action == 'INVERT':
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, img = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
filtered = cv2.bitwise_not(img)
return filtered

Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com