You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python实现图片伪验证API:HTML表单上传触发脚本执行方案

实现员工ID图片伪验证API的完整方案

整体思路

用Python搭建轻量后端服务(以Flask为例),接收前端HTML表单上传的图片,调用形状检测脚本完成伪验证,最终返回结果给前端展示。


1. 后端Python服务实现

1.1 依赖安装

先安装必要的库:

pip install flask opencv-python numpy

1.2 后端代码(app.py)

from flask import Flask, request, jsonify, render_template
import cv2
import numpy as np

app = Flask(__name__)

# 形状检测核心函数(伪验证逻辑)
def validate_id_image(image_path):
    # 读取图片并预处理
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(blurred, 50, 150)

    # 查找轮廓
    contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 检测是否存在指定形状(这里以圆形和正方形为例)
    has_circle = False
    has_square = False

    for contour in contours:
        # 计算轮廓近似
        perimeter = cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, 0.04 * perimeter, True)

        # 判断形状
        if len(approx) == 4:
            # 正方形判断(简单版:长宽比接近1)
            x, y, w, h = cv2.boundingRect(approx)
            aspect_ratio = float(w) / h
            if 0.9 <= aspect_ratio <= 1.1:
                has_square = True
        elif len(approx) > 8:
            # 圆形判断(简单版:轮廓近似多边形的边数多,且周长与直径比接近π)
            area = cv2.contourArea(contour)
            if area > 0:
                circularity = 4 * np.pi * (area / (perimeter ** 2))
                if 0.7 <= circularity <= 1.3:
                    has_circle = True

    # 伪验证规则:同时存在圆形和正方形则通过
    return {"valid": has_circle and has_square, "detected_shapes": {"circle": has_circle, "square": has_square}}

# 处理图片上传的接口
@app.route('/validate', methods=['POST'])
def handle_upload():
    if 'image' not in request.files:
        return jsonify({"error": "未上传图片文件"}), 400
    
    file = request.files['image']
    if file.filename == '':
        return jsonify({"error": "未选择图片"}), 400
    
    # 保存上传的图片到临时路径
    temp_path = 'temp_upload.jpg'
    file.save(temp_path)
    
    # 执行验证
    result = validate_id_image(temp_path)
    
    return jsonify(result)

# 提供前端页面的路由
@app.route('/')
def index():
    return render_template('index.html')

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

2. 前端HTML表单实现

在Flask项目根目录下创建templates文件夹,新建index.html:

<!DOCTYPE html>
<html>
<head>
    <title>员工ID验证</title>
    <style>
        .container {
            max-width: 500px;
            margin: 50px auto;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 8px;
        }
        .result {
            margin-top: 20px;
            padding: 10px;
            border-radius: 4px;
        }
        .valid {
            background-color: #d4edda;
            color: #155724;
        }
        .invalid {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>员工ID图片验证</h2>
        <form id="uploadForm" enctype="multipart/form-data">
            <input type="file" name="image" accept="image/*" required>
            <button type="submit">上传验证</button>
        </form>
        <div id="result" class="result" style="display: none;"></div>
    </div>

    <script>
        document.getElementById('uploadForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const resultDiv = document.getElementById('result');
            
            try {
                const response = await fetch('/validate', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                resultDiv.style.display = 'block';
                if (data.valid) {
                    resultDiv.className = 'result valid';
                    resultDiv.innerHTML = `验证通过!检测到:${data.detected_shapes.circle ? '圆形 ' : ''}${data.detected_shapes.square ? '方形' : ''}`;
                } else {
                    resultDiv.className = 'result invalid';
                    resultDiv.innerHTML = `验证失败!未同时检测到圆形和方形。已检测:${data.detected_shapes.circle ? '圆形 ' : ''}${data.detected_shapes.square ? '方形' : ''}`;
                }
            } catch (error) {
                resultDiv.style.display = 'block';
                resultDiv.className = 'result invalid';
                resultDiv.innerHTML = '验证出错,请重试';
            }
        });
    </script>
</body>
</html>

3. 运行与测试

  1. 确保项目结构正确:
your_project/
├── app.py
└── templates/
    └── index.html
  1. 运行后端服务:
python app.py
  1. 打开浏览器访问http://localhost:5000,上传包含指定形状的员工ID图片,即可看到验证结果。

注意事项

  • 这里的形状检测是伪验证逻辑,实际使用时需根据你的员工ID图案调整检测规则(比如特定尺寸、位置的形状)
  • 临时图片temp_upload.jpg会被每次上传覆盖,若需要保留上传记录,可修改保存逻辑为按时间戳命名
  • 若要部署到生产环境,需关闭Flask的debug=True,并使用WSGI服务器(如Gunicorn)

内容的提问来源于stack exchange,提问作者user25947831

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:30:15