在透明图像周围创建描边

问题描述 投票:0回答:1

我想创建一个模切贴纸设计。在我的应用程序中,用户应该能够上传任何具有透明背景的 png 文件。应用程序应在图像周围创建双边框,看起来像模切贴纸。我尝试使用行进方块算法进行此操作,它适用于具有闭合路径的简单图像,但我在处理多元素图像时遇到问题,我的算法仅关注 1 个元素,但我希望在所有元素周围用一笔画(一,外笔画)就像模切贴纸一样,而不是每个元素都有单独的笔画)。

有什么方法可以使用算法来做到这一点吗?你能帮我修改我的代码吗? 这是一个现有的实现:

https://codesandbox.io/p/sandbox/canvas-sticker-hpqwwy

javascript reactjs image-processing canvas edge-detection
1个回答
0
投票

我尝试使用 dilate 但结果不够好。我决定从图像中删除 Alpha 以使边缘检测更容易,但最终结果仍然不够好。这是结果:

alpha-edges

我期望这样的边框(我自己画的,以显示模切效果):

enter image description here

描边应该平滑,以创建易于打印的模切图像(它消耗删除了 Alpha 的图像)。这是图片:https://i.imgur.com/lXwC8y0.png

from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
import cv2
import base64

app = Flask(__name__)
CORS(app)

@app.route('/process-image', methods=['POST'])
def process_image():
    data = request.get_json()
    if not data or 'image' not in data:
        return 'No image provided', 400

    # Decode the base64 image to numpy array
    image_data = base64.b64decode(data['image'])
    image_array = np.frombuffer(image_data, dtype=np.uint8)
    image = cv2.imdecode(image_array, cv2.IMREAD_GRAYSCALE)

    # Convert image to binary using Otsu's thresholding
    _, binary_image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    # Find contours
    contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Draw contours on a blank canvas
    output_image = np.zeros_like(image)
    cv2.drawContours(output_image, contours, -1, (255), thickness=2)

    # Smooth the contours
    for contour in contours:
        epsilon = 0.01 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)
        cv2.polylines(output_image, [approx], isClosed=True, color=(255), thickness=3)

    _, buffer = cv2.imencode('.png', output_image)
    response_image = base64.b64encode(buffer).decode('utf-8')

    return jsonify({'image': response_image})

if __name__ == '__main__':
    app.run(debug=True, port=5000)
© www.soinside.com 2019 - 2024. All rights reserved.