django - 将 Opencv 与 Django 集成
问题描述
我想将 OpenCV 集成到我的 django 项目中。我不知道该怎么做。我已经阅读了一些教程并自定义了我的代码,如下所示:
图像模型:
import os
import datetime
import uuid
from django.db import models
from django.contrib.auth import get_user_model
from config import abstract_model
from PIL import Image
import numpy as np
from django.core.files.base import ContentFile
from .utils import get_detected_image
from io import BytesIO
User = get_user_model()
class FileManager:
@staticmethod
def photo_path(instance, filename):
basefilename, file_extension = os.path.splitext(filename)
date = datetime.datetime.today()
uid = uuid.uuid4()
return f'Chekced_Images/{instance.user.email}/{uid}-{date}{file_extension}'
class RawImage(abstract_model.BaseAbstractModel):
user = models.ForeignKey(
User,
on_delete=models.DO_NOTHING,
related_name='checked_images'
)
image = models.ImageField(upload_to=FileManager.photo_path,
null=True,
blank=True)
is_detected = models.BooleanField(default=False, blank=True, null=True,)
def __str__(self):
return f'{self.user}\'s checked image on {self.posted_on}'
def save(self, *args, **kwargs):
# Open Image
pil_img = Image.open(self.image)
# convert image to array
cv_img = np.array(pil_img)
# check the image
img = get_detected_image(cv_img)
# convert the image from the array
detected_img = Image.fromarray(img)
# Save image
buffer = BytesIO()
detected_img.save(buffer, format='png')
image_png = buffer.getvalue()
self.image.save(str(self.image), ContentFile(image_png), save=False)
super().save(*args, **kwargs)
物体检测功能如下:
import cv2 as cv
import numpy as np
def get_detected_image(image):
main_image = cv.imread('./needle_image.jpg', cv.IMREAD_REDUCED_COLOR_2)
template = cv.imread('./template_image.jpg', cv.IMREAD_REDUCED_COLOR_2)
result = cv.matchTemplate(main_image, template, cv.TM_CCOEFF_NORMED)
# Get the best match position
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
threshold = 0.8
if max_val >= threshold:
print('Found needle.')
needle_w = template.shape[1]
needle_h = template.shape[0]
top_left = max_loc
bottom_right = (top_left[0] + needle_w, top_left[1] + needle_h)
cv.rectangle(main_image,
top_left,
bottom_right,
color=(0, 255, 0),
thickness=2,
lineType=cv.LINE_8)
return cv.imwrite('result.jpg', main_image)
注意: 我正在做我最后一年的项目。因此,请帮助我如何将此功能实现到我的 django 项目中。我遵循了一些 YouTube 教程并收集了这么多代码。如果有任何简单的方法来实现这一点,请提出一个。
解决方案
推荐阅读
- r - 如何创建均值测试表和交叉表
- python - Django 查询功能没有正确过滤用户类型
- mysql - 添加事务以续集创建模块
- android - 当我将 App Theme 更改为 Material Theme 时,Android SDK 的 Button 被 MaterialButton 取代
- python - 如何根据python中给出的命令行输入运行某些功能
- html - HTML/CSS 固定元素在滚动时不会隐藏其他元素
- clang - clang sanitize-blacklist 没有忽略一个函数
- html - 标题 + 粘性侧边栏
- homebrew - 我无法使用 Homebrew 和 .zsh 在 MacOS X 上安装 Miniconda
- excel - 将特定值输入特定单元格时如何返回时间戳