>  기사  >  백엔드 개발  >  Python 및 OpenCV를 사용하여 가장자리 감지 구현: 단계별 가이드

Python 및 OpenCV를 사용하여 가장자리 감지 구현: 단계별 가이드

DDD
DDD원래의
2024-10-20 06:10:02877검색

소개

가장자리 감지는 컴퓨터 비전의 기본이므로 이미지 내 객체 경계를 식별할 수 있습니다. 이 튜토리얼에서는 Python 및 OpenCV와 함께 Sobel 연산자와 Canny 가장자리 감지기를 사용하여 가장자리 감지를 구현합니다. 그런 다음 사용자가 이미지를 업로드하고 결과를 볼 수 있도록 Bootstrap 스타일의 Flask를 사용하는 간단한 웹 애플리케이션을 만듭니다.

데모 링크: 가장자리 감지 데모

전제 조건

  • 컴퓨터에 Python 3.x가 설치되어 있습니다.
  • Python 프로그래밍에 대한 기본 지식
  • HTML과 CSS에 익숙하면 도움이 되지만 필수는 아닙니다.

환경 설정

1. 필수 라이브러리 설치

터미널이나 명령 프롬프트를 열고 다음을 실행하세요.

pip install opencv-python numpy Flask

2. 프로젝트 디렉토리 생성

mkdir edge_detection_app
cd edge_detection_app

가장자리 감지 구현

1. 소벨 연산자

Sobel 연산자는 가장자리를 강조하면서 이미지 강도의 기울기를 계산합니다.

코드 구현:

import cv2

# Load the image in grayscale
image = cv2.imread('input_image.jpg', cv2.IMREAD_GRAYSCALE)
if image is None:
    print("Error loading image")
    exit()

# Apply Sobel operator
sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=5)  # Horizontal edges
sobely = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=5)  # Vertical edges

2. Canny Edge 감지기

Canny 엣지 검출기는 엣지 검출을 위한 다단계 알고리즘입니다.

코드 구현:

# Apply Canny edge detector
edges = cv2.Canny(image, threshold1=100, threshold2=200)

Flask 웹 애플리케이션 만들기

1. Flask 앱 설정

app.py라는 파일을 만듭니다.

from flask import Flask, request, render_template, redirect, url_for
import cv2
import os

app = Flask(__name__)

UPLOAD_FOLDER = 'static/uploads/'
OUTPUT_FOLDER = 'static/outputs/'

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER

# Create directories if they don't exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(OUTPUT_FOLDER, exist_ok=True)

2. 경로 정의

업로드 경로:

@app.route('/', methods=['GET', 'POST'])
def upload_image():
    if request.method == 'POST':
        file = request.files.get('file')
        if not file or file.filename == '':
            return 'No file selected', 400
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)
        process_image(file.filename)
        return redirect(url_for('display_result', filename=file.filename))
    return render_template('upload.html')

이미지 처리 기능:

def process_image(filename):
    image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # Apply edge detection
    sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=5)
    edges = cv2.Canny(image, 100, 200)

    # Save outputs
    cv2.imwrite(os.path.join(app.config['OUTPUT_FOLDER'], 'sobelx_' + filename), sobelx)
    cv2.imwrite(os.path.join(app.config['OUTPUT_FOLDER'], 'edges_' + filename), edges)

결과 경로:

@app.route('/result/<filename>')
def display_result(filename):
    return render_template('result.html',
                           original_image='uploads/' + filename,
                           sobelx_image='outputs/sobelx_' + filename,
                           edges_image='outputs/edges_' + filename)

3. 앱 실행

if __name__ == '__main__':
    app.run(debug=True)

부트스트랩을 사용하여 웹 애플리케이션 스타일 지정

스타일 지정을 위해 HTML 템플릿에 Bootstrap CDN을 포함하세요.

1. 업로드.html

템플릿 디렉토리를 만들고 upload.html을 추가하세요.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edge Detection App</title>
    <!-- Bootstrap CSS CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center mb-4">Upload an Image for Edge Detection</h1>
        <div class="row justify-content-center">
            <div class="col-md-6">
                <form method="post" enctype="multipart/form-data" class="border p-4">
                    <div class="form-group">
                        <label for="file">Choose an image:</label>
                        <input type="file" name="file" accept="image/*" required class="form-control-file" id="file">
                    </div>
                    <button type="submit" class="btn btn-primary btn-block">Upload and Process</button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

2. 결과.html

템플릿 디렉터리에 result.html을 만듭니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edge Detection Results</title>
    <!-- Bootstrap CSS CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center mb-5">Edge Detection Results</h1>
        <div class="row">
            <div class="col-md-6 mb-4">
                <h4 class="text-center">Original Image</h4>
                <img src="{{ url_for('static', filename=original_image) }}" alt="Original Image" class="img-fluid rounded mx-auto d-block">
            </div>
            <div class="col-md-6 mb-4">
                <h4 class="text-center">Sobel X</h4>
                <img src="{{ url_for('static', filename=sobelx_image) }}" alt="Sobel X" class="img-fluid rounded mx-auto d-block">
            </div>
            <div class="col-md-6 mb-4">
                <h4 class="text-center">Canny Edges</h4>
                <img src="{{ url_for('static', filename=edges_image) }}" alt="Canny Edges" class="img-fluid rounded mx-auto d-block">
            </div>
        </div>
        <div class="text-center mt-4">
            <a href="{{ url_for('upload_image') }}" class="btn btn-secondary">Process Another Image</a>
        </div>
    </div>
</body>
</html>

애플리케이션 실행 및 테스트

1. 플라스크 앱 실행

python app.py

2. 애플리케이션 접속

웹 브라우저를 열고 http://localhost:5000으로 이동하세요.

  • 이미지를 업로드하고 업로드 및 처리를 클릭하세요.
  • 가장자리 감지 결과를 확인하세요.

샘플 결과

Implementing Edge Detection with Python and OpenCV: A Step-by-Step Guide

결론

Sobel 연산자와 Canny 가장자리 감지기를 사용하여 가장자리 감지를 수행하는 간단한 웹 애플리케이션을 구축했습니다. Python, OpenCV, Flask 및 Bootstrap을 통합하여 사용자가 이미지를 업로드하고 가장자리 감지 결과를 볼 수 있는 대화형 도구를 만들었습니다.

다음 단계

  • 애플리케이션 강화: 더 많은 가장자리 감지 옵션을 추가하거나 매개변수 조정을 허용합니다.
  • UI 개선: 더 나은 사용자 경험을 위해 더 많은 Bootstrap 구성요소를 통합합니다.
  • 추가 탐색: Heroku 또는 AWS와 같은 다른 플랫폼에 앱을 배포하세요.

GitHub 저장소: 가장자리 감지 앱

위 내용은 Python 및 OpenCV를 사용하여 가장자리 감지 구현: 단계별 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.