首页 > 解决方案 > 将 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 教程并收集了这么多代码。如果有任何简单的方法来实现这一点,请提出一个。

标签: djangoobject-detectionopencv-python

解决方案


推荐阅读