Khắc Phục Sự Cố

CAPTCHA hình ảnh trả về câu trả lời sai: Tối ưu hóa chất lượng

Nếu CaptchaAI trả về câu trả lời không chính xác cho CAPTCHA hình ảnh thì vấn đề hầu như luôn nằm ở hình ảnh được gửi chứ không phải cách giải quyết. Đây là cách chẩn đoán và khắc phục nó.


Nguyên nhân phổ biến của câu trả lời sai

nguyên nhân Tần số sửa chữa
Hình ảnh bị cắt không chính xác Rất phổ biến Chụp đầy đủ phần tử CAPTCHA
Độ phân giải/nén thấp chung Gửi hình ảnh chất lượng cao hơn
Mã hóa hình ảnh sai chung Xác minh mã hóa base64
Thiếu ngôn ngữ/type gợi ý Thỉnh thoảng Thêm language hoặc textinstructions
Hình ảnh cũ/expired Thỉnh thoảng Chụp ảnh tươi trước khi giải

Cách khắc phục 1: Xác minh chất lượng hình ảnh trước khi gửi

import base64
from io import BytesIO
from PIL import Image

def validate_captcha_image(image_path):
    """Check image quality before submitting to CaptchaAI."""
    img = Image.open(image_path)
    width, height = img.size
    issues = []

    # Minimum resolution
    if width < 50 or height < 20:
        issues.append(f"Too small: {width}x{height}px (min 50x20)")

    # Check if mostly blank
    pixels = list(img.getdata())
    if img.mode == "RGB":
        white_count = sum(1 for p in pixels if p[0] > 250 and p[1] > 250 and p[2] > 250)
    else:
        white_count = sum(1 for p in pixels if p > 250)

    blank_ratio = white_count / len(pixels)
    if blank_ratio > 0.95:
        issues.append(f"Image appears blank ({blank_ratio:.0%} white)")

    # File size check
    img_bytes = BytesIO()
    img.save(img_bytes, format="PNG")
    size_kb = img_bytes.tell() / 1024
    if size_kb < 1:
        issues.append(f"File too small ({size_kb:.1f} KB) — may be empty")
    if size_kb > 600:
        issues.append(f"File too large ({size_kb:.0f} KB) — submit under 600 KB")

    return issues

issues = validate_captcha_image("captcha.png")
if issues:
    for issue in issues:
        print(f"WARNING: {issue}")
else:
    print("Image quality OK")

Cách 2: Mã hóa Base64 đúng

import base64

def encode_captcha(image_path):
    """Properly encode a CAPTCHA image to base64."""
    with open(image_path, "rb") as f:
        raw = f.read()

    encoded = base64.b64encode(raw).decode("ascii")

    # Verify round-trip
    decoded = base64.b64decode(encoded)
    assert decoded == raw, "Base64 encoding corrupted the image"

    return encoded

# WRONG — encoding a file path string
bad = base64.b64encode(b"captcha.png").decode()  # Encodes filename, not image!

# CORRECT — encoding file contents
with open("captcha.png", "rb") as f:
    good = base64.b64encode(f.read()).decode()

Cách 3: Xử lý sơ bộ ảnh

from PIL import Image, ImageFilter, ImageEnhance
from io import BytesIO
import base64

def preprocess_captcha(image_path):
    """Improve image quality for better OCR accuracy."""
    img = Image.open(image_path)

    # Convert to RGB if needed
    if img.mode != "RGB":
        img = img.convert("RGB")

    # Upscale small images
    width, height = img.size
    if width < 200:
        scale = 200 / width
        img = img.resize(
            (int(width * scale), int(height * scale)),
            Image.LANCZOS,
        )

    # Increase contrast
    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(1.5)

    # Sharpen
    img = img.filter(ImageFilter.SHARPEN)

    # Convert to PNG bytes
    buffer = BytesIO()
    img.save(buffer, format="PNG")
    return base64.b64encode(buffer.getvalue()).decode()

Cách 4: Thêm gợi ý về loại và ngôn ngữ

import requests

def solve_image(api_key, image_base64, **hints):
    """Submit image CAPTCHA with quality hints."""
    data = {
        "key": api_key,
        "method": "base64",
        "body": image_base64,
        "json": 1,
    }

    # Add optional hints for better accuracy
    if "language" in hints:
        data["language"] = hints["language"]  # 0=default, 1=Cyrillic, 2=Latin
    if "textinstructions" in hints:
        data["textinstructions"] = hints["textinstructions"]
    if "numeric" in hints:
        data["numeric"] = hints["numeric"]  # 1=digits only, 2=letters only
    if "min_len" in hints:
        data["min_len"] = hints["min_len"]
    if "max_len" in hints:
        data["max_len"] = hints["max_len"]

    resp = requests.post("https://ocr.captchaai.com/in.php", data=data, timeout=30)
    return resp.json()

# Example: Digits-only CAPTCHA, 4-6 characters
result = solve_image(
    "YOUR_API_KEY",
    encoded_image,
    numeric=1,
    min_len=4,
    max_len=6,
)

# Example: Case-sensitive text
result = solve_image(
    "YOUR_API_KEY",
    encoded_image,
    textinstructions="Case-sensitive, enter exactly as shown",
)

Cách 5: Chụp toàn bộ phần tử CAPTCHA

from selenium import webdriver
from selenium.webdriver.common.by import By
import base64

def capture_captcha_element(driver, selector):
    """Screenshot only the CAPTCHA element, not the full page."""
    element = driver.find_element(By.CSS_SELECTOR, selector)

    # Element screenshot (better than page crop)
    png_bytes = element.screenshot_as_png

    # Verify it's not empty
    if len(png_bytes) < 500:
        raise ValueError("Screenshot too small — element may not be visible")

    return base64.b64encode(png_bytes).decode()

# Usage
driver = webdriver.Chrome()
driver.get("https://example.com")
image_b64 = capture_captcha_element(driver, "img#captchaImage")

Cách khắc phục 6: Xử lý CAPTCHA Dynamic/Rotating

import time

def solve_with_fresh_image(driver, api_key, captcha_selector):
    """Capture and solve CAPTCHA immediately to avoid expiry."""
    # Wait for CAPTCHA to load fully
    time.sleep(2)

    # Capture fresh
    element = driver.find_element(By.CSS_SELECTOR, captcha_selector)
    png_bytes = element.screenshot_as_png
    body = base64.b64encode(png_bytes).decode()

    # Submit immediately
    resp = requests.post("https://ocr.captchaai.com/in.php", data={
        "key": api_key,
        "method": "base64",
        "body": body,
        "json": 1,
    }, timeout=30)
    result = resp.json()

    if result.get("status") != 1:
        raise RuntimeError(result.get("request"))

    task_id = result["request"]

    # Poll — image CAPTCHAs solve fast
    time.sleep(5)
    for _ in range(12):
        resp = requests.get("https://ocr.captchaai.com/res.php", params={
            "key": api_key, "action": "get",
            "id": task_id, "json": 1,
        }, timeout=15)
        data = resp.json()

        if data.get("status") == 1:
            return data["request"]
        if data["request"] != "CAPCHA_NOT_READY":
            raise RuntimeError(data["request"])
        time.sleep(3)

    raise TimeoutError("Image solve timeout")

Danh sách kiểm tra khắc phục sự cố

Triệu chứng Chẩn đoán sửa chữa
Câu trả lời thật lố bịch Mã hóa Base64 sai Xác minh mã hóa khứ hồi
Đáp án gần nhưng sai Chất lượng hình ảnh thấp Tiền xử lý: cao cấp, sắc nét, tương phản
Câu trả lời có số ký tự sai Gợi ý độ dài bị thiếu Thêm tham số min_len/max_len
Trả lời kết hợp các chữ cái/digits Thiếu gợi ý loại Thêm số=1 hoặc số=2
Câu trả lời trống được trả về Hình ảnh Blank/corrupted Xác thực hình ảnh trước khi gửi
Câu trả lời đúng nhưng trang web từ chối Phân biệt chữ hoa chữ thường Thêm văn bản hướng dẫn cho trường hợp

Câu hỏi thường gặp

CaptchaAI đối với CAPTCHA hình ảnh có độ chính xác như thế nào?

Với hình ảnh được gửi đúng cách, CaptchaAI hỗ trợ hơn 27.500 loại CAPTCHA với độ chính xác cao. Hầu hết các lỗi xảy ra là do chất lượng hình ảnh kém hoặc thông số không chính xác.

Tôi có nên xử lý trước hình ảnh trước khi gửi không?

Chỉ khi hình ảnh gốc có chất lượng thấp. CaptchaAI xử lý tốt hình ảnh CAPTCHA tiêu chuẩn mà không cần xử lý trước. Nâng cấp hình ảnh rất nhỏ và tăng độ tương phản có thể giúp ích cho các trường hợp khó khăn.

Tôi có thể báo cáo câu trả lời sai không?

Đúng. Sử dụng điểm cuối reportbad với ID nhiệm vụ để báo cáo câu trả lời sai. Điều này giúp cải thiện độ chính xác và có thể ghi có vào tài khoản của bạn.


Hướng dẫn liên quan


Giải quyết hình ảnh một cách chính xác —hãy thử CaptchaAI.

Os comentários estão desativados para este artigo.