Files
aiData/debug_cv.py
HuangHai 9e610b1906 'commit'
2026-01-14 13:14:05 +08:00

94 lines
3.4 KiB
Python

import sys
import os
import cv2
import numpy as np
sys.path.append(os.getcwd())
from Apps.TeLaiDian.Kit import detect_cards_cv as real_detect_cards_cv
from Apps.TeLaiDian.Config.Setting import SAFE_EXCLUDE_RATIO, BOTTOM_SAFE_EXCLUDE_RATIO
def read_image(path):
if not path or not os.path.exists(path):
return None
try:
data = np.fromfile(path, dtype=np.uint8)
if data.size == 0:
return None
img = cv2.imdecode(data, -1)
return img
except Exception as e:
print(f"Error reading image {path}: {e}")
return None
def detect_cards_cv(image_path, top_ratio=None, bottom_ratio=None):
if top_ratio is None:
top_ratio = SAFE_EXCLUDE_RATIO
if bottom_ratio is None:
bottom_ratio = BOTTOM_SAFE_EXCLUDE_RATIO
MIN_CARD_HEIGHT = 150 # Assuming default from Setting
img = read_image(image_path)
if img is None:
print("Image not found or invalid")
return []
h, w = img.shape[:2]
print(f"Image Size: {w}x{h}")
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 限制检测范围
top_limit = int(h * top_ratio)
bottom_limit = int(h * (1 - bottom_ratio))
print(f"CV limits: top={top_limit}, bottom={bottom_limit}, threshold_y={int(h * 0.58)}")
# 使用自适应阈值
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
# 闭运算
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (w // 4, 3))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# 寻找轮廓
contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
min_card_width = int(w * 0.8)
for cnt in contours:
x, y, cw, ch = cv2.boundingRect(cnt)
center_y = y + ch // 2
rect_area = cw * ch
cnt_area = cv2.contourArea(cnt)
extent = cnt_area / rect_area if rect_area > 0 else 0
approx = cv2.approxPolyDP(cnt, 0.02 * cv2.arcLength(cnt, True), True)
ok_width = cw >= min_card_width
ok_height = ch > MIN_CARD_HEIGHT * 0.8
ok_vertical = center_y >= int(h * 0.58) and y > top_limit and y + ch < bottom_limit
# Check green ratio
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
roi = hsv[max(0,y):min(h,y+ch), max(0,x):min(w,x+cw)]
green_mask = cv2.inRange(roi, np.array([35, 80, 80]), np.array([85, 255, 255]))
green_ratio = float(cv2.countNonZero(green_mask)) / (roi.shape[0]*roi.shape[1]) if roi.size > 0 else 0.0
ok_color = green_ratio < 0.25
if cw > w * 0.5: # Only print large enough boxes
print(f"Box: y={y}, h={ch}, w={cw}, center_y={center_y}, extent={extent:.2f}, green={green_ratio:.2f}")
print(f" Checks: width={ok_width}, height={ok_height}, vertical={ok_vertical}, color={ok_color}")
image_path = r"d:\dsWork\aiData\Output\tld_list_1768359492_flag.jpg"
# Try the original if flag doesn't exist or is modified
original_path = r"d:\dsWork\aiData\Output\tld_list_1768359492.jpg"
if os.path.exists(original_path):
print(f"Testing original image: {original_path}")
detect_cards_cv(original_path)
else:
print(f"Original image not found, trying flag: {image_path}")
detect_cards_cv(image_path)