test: 移除快速测试 API 和人脸检测测试脚本及所有相关测试图片。
This commit is contained in:
parent
b5d0a66249
commit
4230e62f0a
Binary file not shown.
|
Before Width: | Height: | Size: 275 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 380 KiB |
|
|
@ -1,103 +0,0 @@
|
|||
|
||||
import requests
|
||||
import json
|
||||
import cv2
|
||||
import numpy as np
|
||||
import os
|
||||
|
||||
# 配置服务地址
|
||||
JAVA_BACKEND_URL = "http://localhost:18080"
|
||||
PYTHON_ALGO_URL = "http://localhost:18000"
|
||||
|
||||
def create_test_image(filename="test_face.jpg"):
|
||||
"""创建一张简单的测试图片(如果不存在)"""
|
||||
if not os.path.exists(filename):
|
||||
print(f"Creating test image: {filename}...")
|
||||
# 创建一个 640x480 的黑色图像
|
||||
img = np.zeros((480, 640, 3), np.uint8)
|
||||
# 画一个简单的圆代表"脸" (虽然检测不到,但可以测试文件上传流程)
|
||||
cv2.circle(img, (320, 240), 100, (255, 255, 255), -1)
|
||||
cv2.imwrite(filename, img)
|
||||
return filename
|
||||
|
||||
def test_python_health():
|
||||
"""测试 Python 算法服务健康检查"""
|
||||
url = f"{PYTHON_ALGO_URL}/health"
|
||||
print(f"\n[Testing] Python Algorithm Service Health ({url})...")
|
||||
try:
|
||||
response = requests.get(url, timeout=5)
|
||||
if response.status_code == 200:
|
||||
print(f"✅ Success: {response.json()}")
|
||||
else:
|
||||
print(f"❌ Failed: Status {response.status_code}, Response: {response.text}")
|
||||
except requests.exceptions.ConnectionError:
|
||||
print("❌ Failed: Connection refused. Is the service running on port 18000?")
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
|
||||
def test_extract_feature(image_path):
|
||||
"""测试人脸特征提取接口"""
|
||||
url = f"{PYTHON_ALGO_URL}/api/extract_feature"
|
||||
print(f"\n[Testing] Face Feature Extraction ({url})...")
|
||||
|
||||
if not os.path.exists(image_path):
|
||||
print("❌ Error: Test image not found.")
|
||||
return
|
||||
|
||||
try:
|
||||
with open(image_path, 'rb') as f:
|
||||
files = {'image': f}
|
||||
response = requests.post(url, files=files, timeout=10)
|
||||
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
if result.get('success'):
|
||||
dim = result.get('feature_dim')
|
||||
print(f"✅ Success: Feature extracted. Dimension: {dim}")
|
||||
else:
|
||||
# 预期内失败,因为我们的假脸可能过不了检测,但这证明接口通了
|
||||
print(f"⚠️ Service Reachable (Logic Result): {result.get('message')}")
|
||||
else:
|
||||
print(f"❌ Failed: Status {response.status_code}, Response: {response.text}")
|
||||
except requests.exceptions.ConnectionError:
|
||||
print("❌ Failed: Connection refused.")
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
|
||||
def test_java_group_list():
|
||||
"""测试 Java 后端分组列表接口"""
|
||||
url = f"{JAVA_BACKEND_URL}/api/groups/list"
|
||||
print(f"\n[Testing] Java Backend Group List ({url})...")
|
||||
try:
|
||||
response = requests.get(url, timeout=5)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
if data.get('code') == 200:
|
||||
print(f"✅ Success: Retrieved {len(data.get('data', []))} groups.")
|
||||
print(f" Response: {json.dumps(data, ensure_ascii=False)}")
|
||||
else:
|
||||
print(f"❌ Functional Error: {data}")
|
||||
else:
|
||||
print(f"❌ Failed: Status {response.status_code}, Response: {response.text}")
|
||||
except requests.exceptions.ConnectionError:
|
||||
print("❌ Failed: Connection refused. Is the service running on port 18080?")
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("=== Face Recognition System Quick Test ===")
|
||||
|
||||
# 1. 准备测试图片
|
||||
test_img = create_test_image()
|
||||
|
||||
# 2. 测试算法服务
|
||||
test_python_health()
|
||||
test_extract_feature(test_img)
|
||||
|
||||
# 3. 测试Java后端
|
||||
test_java_group_list()
|
||||
|
||||
print("\n=== Test Finished ===")
|
||||
# 清理生成的测试图 (可选,这里保留以便用户查看)
|
||||
# if os.path.exists(test_img):
|
||||
# os.remove(test_img)
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 126 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.8 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.8 MiB |
|
|
@ -1,126 +0,0 @@
|
|||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
import os
|
||||
import json
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
# 配置服务地址
|
||||
PYTHON_ALGO_URL = "http://192.168.0.37:18000"
|
||||
|
||||
def get_default_image_path():
|
||||
"""获取一个默认存在的测试图片路径"""
|
||||
# 尝试找一个存在的真实图片
|
||||
potential_paths = [
|
||||
r"C:\Users\24830\Desktop\人脸.jpg",
|
||||
]
|
||||
for path in potential_paths:
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
return None
|
||||
|
||||
def detect_and_draw(image_path, expand_scale=0.0):
|
||||
url = f"{PYTHON_ALGO_URL}/api/detect_face"
|
||||
print(f"\n[Processing] Image: {image_path}")
|
||||
print(f"[API URL] {url}")
|
||||
print(f"[Expand Scale] {expand_scale}")
|
||||
|
||||
if not os.path.exists(image_path):
|
||||
print(f"❌ Error: Image file not found: {image_path}")
|
||||
return
|
||||
|
||||
try:
|
||||
# 1. 准备发送请求
|
||||
# 读取图片用于显示/画框
|
||||
img_array = np.fromfile(image_path, dtype=np.uint8)
|
||||
original_img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
|
||||
|
||||
if original_img is None:
|
||||
print(f"❌ Error: Failed to read image using opencv: {image_path}")
|
||||
return
|
||||
|
||||
# 2. 调用API
|
||||
data = {'expand_scale': expand_scale}
|
||||
with open(image_path, 'rb') as f:
|
||||
files = {'image': f}
|
||||
# 注意: 使用 data=data 发送表单数据,而不是 params=params (查询参数)
|
||||
response = requests.post(url, files=files, data=data, timeout=10)
|
||||
|
||||
if response.status_code != 200:
|
||||
print(f"❌ Failed: Status {response.status_code}, Response: {response.text}")
|
||||
return
|
||||
|
||||
result = response.json()
|
||||
print("\n=== API Response ===")
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
# 3. 处理结果并画图
|
||||
if result.get('success'):
|
||||
faces = result.get('faces', [])
|
||||
count = len(faces)
|
||||
print(f"\n✅ Success: Detected {count} faces.")
|
||||
|
||||
# 创建副本用于画图
|
||||
draw_img = original_img.copy()
|
||||
|
||||
for i, face in enumerate(faces):
|
||||
x1 = int(face['x1'])
|
||||
y1 = int(face['y1'])
|
||||
x2 = int(face['x2'])
|
||||
y2 = int(face['y2'])
|
||||
score = face['score']
|
||||
|
||||
# 画矩形框
|
||||
# 颜色 (B, G, R) - 绿色
|
||||
color = (0, 255, 0)
|
||||
thickness = 2
|
||||
cv2.rectangle(draw_img, (x1, y1), (x2, y2), color, thickness)
|
||||
|
||||
# 写文字
|
||||
label = f"Face {i+1}: {score:.2f}"
|
||||
cv2.putText(draw_img, label, (x1, y1 - 10),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
|
||||
|
||||
print(f" - Face {i+1}: Box({x1}, {y1}, {x2}, {y2}), Score: {score:.4f}")
|
||||
|
||||
# 保存裁剪的人脸图观察效果
|
||||
face_crop = original_img[y1:y2, x1:x2]
|
||||
if face_crop.size > 0:
|
||||
crop_filename = f"face_crop_{i+1}_scale_{expand_scale}.jpg"
|
||||
cv2.imencode('.jpg', face_crop)[1].tofile(crop_filename)
|
||||
print(f" Saved crop: {crop_filename}")
|
||||
|
||||
# 4. 保存结果图
|
||||
output_filename = f"result_detected_scale_{expand_scale}.jpg"
|
||||
cv2.imencode('.jpg', draw_img)[1].tofile(output_filename)
|
||||
print(f"\n✅ Result image saved to: {os.path.abspath(output_filename)}")
|
||||
|
||||
else:
|
||||
print(f"⚠️ API logic returned failure: {result.get('message')}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description='Face Detection API Test Script')
|
||||
parser.add_argument('image_path', nargs='?', help='Path to the image file')
|
||||
parser.add_argument('--scale', type=float, default=0.6, help='Expand scale (default: 0.0)')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
target_path = args.image_path
|
||||
|
||||
if not target_path:
|
||||
default_path = get_default_image_path()
|
||||
if default_path:
|
||||
print(f"No image path provided, using default found: {default_path}")
|
||||
target_path = default_path
|
||||
else:
|
||||
print("Usage: python test_detect_face.py <path_to_image> [--scale 0.3]")
|
||||
print("Error: No image path provided and no default test image found.")
|
||||
sys.exit(1)
|
||||
|
||||
detect_and_draw(target_path, args.scale)
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
|
||||
# 配置
|
||||
BASE_URL = "http://localhost:18080/api"
|
||||
GROUP_NAME = "TestGroup_Verify"
|
||||
USER_NAME = "DuplicateTestUser"
|
||||
TEST_IMG = "verify_face.jpg"
|
||||
|
||||
def create_test_image():
|
||||
if not os.path.exists(TEST_IMG):
|
||||
# 创建一个简单的dummy文件
|
||||
with open(TEST_IMG, 'wb') as f:
|
||||
f.write(b'\xFF\xD8\xFF\xE0' + b'\x00' * 1000) # Fake JPG header
|
||||
return TEST_IMG
|
||||
|
||||
def run_verification():
|
||||
print("=== 开始验证 ===")
|
||||
|
||||
# 1. 创建测试分组
|
||||
print("\n1. 创建分组...")
|
||||
resp = requests.post(f"{BASE_URL}/groups/add", json={"name": GROUP_NAME})
|
||||
if resp.status_code == 200 and resp.json()['code'] == 200:
|
||||
group_id = resp.json()['data']['id']
|
||||
print(f"✅ 分组创建成功 ID: {group_id}")
|
||||
else:
|
||||
print(f"❌ 分组创建失败: {resp.text}")
|
||||
return
|
||||
|
||||
# 准备图片
|
||||
create_test_image()
|
||||
files = {'photo': open(TEST_IMG, 'rb')}
|
||||
|
||||
# 2. 添加用户 (第一次)
|
||||
print("\n2. 添加用户 (预期成功)...")
|
||||
data = {"name": USER_NAME, "groupId": group_id}
|
||||
# Re-open file for each request
|
||||
resp = requests.post(f"{BASE_URL}/users/add", data=data, files={'photo': open(TEST_IMG, 'rb')})
|
||||
|
||||
if resp.status_code == 200 and resp.json()['code'] == 200:
|
||||
print(f"✅ 用户创建成功")
|
||||
else:
|
||||
# 如果是因为测试图片无法提取特征而失败,也是预期的(说明代码跑到了特征提取那一步)
|
||||
# 但我们主要验证重名逻辑,所以这里假设如果失败是因为重名则是有问题,如果是因为特征提取则是环境问题
|
||||
print(f"⚠️ 用户创建返回: {resp.json().get('msg')}")
|
||||
|
||||
# 3. 添加同名用户 (预期失败)
|
||||
print("\n3. 再次添加同名用户 (预期被拦截)...")
|
||||
resp = requests.post(f"{BASE_URL}/users/add", data=data, files={'photo': open(TEST_IMG, 'rb')})
|
||||
|
||||
res_json = resp.json()
|
||||
if res_json.get('code') != 200 and "已存在" in str(res_json.get('msg')):
|
||||
print(f"✅ 成功拦截重名用户: {res_json.get('msg')}")
|
||||
else:
|
||||
print(f"❌ 拦截失败或错误信息不匹配: {resp.text}")
|
||||
|
||||
# 4. 测试搜索接口
|
||||
print("\n4. 测试人脸搜索接口...")
|
||||
try:
|
||||
resp = requests.post(f"{BASE_URL}/users/search", data={"groupId": group_id}, files={'photo': open(TEST_IMG, 'rb')})
|
||||
if resp.status_code == 200:
|
||||
print(f"✅ 接口调用成功: {resp.json()}")
|
||||
elif resp.status_code == 404:
|
||||
print(f"✅ 接口调用成功 (未找到匹配 - 符合预期): {resp.json()}")
|
||||
else:
|
||||
print(f"❌ 接口调用异常: {resp.status_code} - {resp.text}")
|
||||
except Exception as e:
|
||||
print(f"❌ 请求异常: {e}")
|
||||
|
||||
print("\n=== 验证结束 ===")
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
run_verification()
|
||||
except Exception as e:
|
||||
print(f"Fatal Error: {e}")
|
||||
Loading…
Reference in New Issue