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

Python图像处理:保留红与白背景并提取数字分步指导

Hey there! Let's work through this step by step—since you're new to programming, I'll break everything down so you understand what's happening at each stage, not just copy-paste code.

First, let's spot the small issues in your current code that are causing problems:

  • OpenCV reads images in BGR format (blue-green-red), not the RGB you might be used to. So your color value for red is reversed.
  • Your code only targets exact pixel values, but noise is almost always a range of colors, not a single one. We need a more flexible way to filter colors.
Step 1: Fix Color Filtering to Keep Red + White, Remove Noise

We'll use the HSV color space instead of BGR—it's way easier to define ranges of colors (like all shades of red) rather than exact pixel values. Here's the adjusted code with explanations:

import cv2
import numpy as np

# Load the image (double-check the file path matches where your image is!)
img = cv2.imread('Output.png')
if img is None:
    print("Error: Couldn't load 'Output.png'—make sure it's in the same folder as your script!")
    exit()

# Convert image to HSV (better for color-based filtering)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Define ranges for ALL shades of red (red wraps around the HSV hue scale, so we need two ranges)
lower_red1 = np.array([0, 50, 50])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([170, 50, 50])
upper_red2 = np.array([180, 255, 255])

# Create masks to isolate red pixels
red_mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
red_mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
red_mask = red_mask1 | red_mask2  # Combine both red ranges

# Define range for white background (bright, low-saturation pixels)
lower_white = np.array([0, 0, 200])
upper_white = np.array([180, 25, 255])
white_mask = cv2.inRange(hsv, lower_white, upper_white)

# Combine masks: keep only red or white pixels
keep_mask = red_mask | white_mask

# Create a pure white background to replace noise
white_bg = np.ones_like(img) * 255

# Keep red/white pixels, turn everything else white (matching your background)
result = np.where(keep_mask[:, :, np.newaxis] == 255, img, white_bg)

# Optional (but critical for OCR): Convert to high-contrast black/white
gray = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)  # Invert so numbers are black on white

# Save processed images
cv2.imwrite('red_numerals_result.jpg', result)
cv2.imwrite('red_numerals_thresh.jpg', thresh)

What this does:

  • HSV separates color, brightness, and saturation, so we can catch all red shades instead of just one exact pixel value.
  • The keep_mask ensures we only keep your red content and white background—all noise gets replaced with white.
  • The threshold step converts the image to pure black-and-white, which is essential for Tesseract to read numbers accurately.
Step 2: Fix the Tesseract Extraction Code

Your OCR code was missing key imports and could use small tweaks for reliability. Here's the corrected version:

import pytesseract
from PIL import Image

def getCaptcha(img_path):
    # Point to your Tesseract installation path (update this if yours is different!)
    pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
    try:
        img = Image.open(img_path)
        # Config tells Tesseract to look for single characters, only numbers
        text = pytesseract.image_to_string(
            img, 
            lang='eng',
            config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789'
        )
        # Remove extra spaces/newlines from the result
        return text.strip()
    except Exception as e:
        print(f"Oops, something went wrong: {e}")
        return ""

# Test with the thresholded image first (it works best for OCR!)
print("Thresholded image result:", getCaptcha('red_numerals_thresh.jpg'))
print("Colored result image:", getCaptcha('red_numerals_result.jpg'))

Key fixes:

  • Added missing imports (pytesseract and PIL.Image)—a common beginner oversight!
  • Added error handling to help you debug if the image isn't found or Tesseract acts up.
  • Used strip() to clean up any extra whitespace Tesseract might return.
  • The thresholded image will give far better results than the colored one, since Tesseract thrives on high-contrast black-and-white.
Step 3: Troubleshooting Tips for Beginners

If things still aren't working, check these common issues:

  • Image not loading: Use the full file path (e.g., C:\\Users\\YourName\\Desktop\\Output.png) if your image isn't in the same folder as your script.
  • Tesseract not found: Double-check the path to tesseract.exe—if you installed it in a custom folder, update that line.
  • Bad OCR results: Adjust the threshold value (the 127 in cv2.threshold) or tweak the HSV ranges if your red is darker/lighter. You can also add a blur step before thresholding: blurred = cv2.GaussianBlur(gray, (3,3), 0) then use blurred instead of gray.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:46:18