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

求助:如何编写条件语句判断图像ROI像素值范围并输出状态

Fixing ROI Pixel Range Check for Status Display

Hey there! Let's sort out that condition for your ROI pixel check. The main thing to note is that your ROI variable is a 2D array of pixels (not a single color value), so we can't just compare it directly to a range. We need to check how many pixels in the ROI fall within your target color bounds, then use that to decide which status to show.

Here's the corrected code with explanations:

import cv2
import numpy as np

frame = cv2.imread('frame 8 sec.jpg')
ROI = frame[450:500, 380:391]

# Define your color range (note: OpenCV uses BGR order, not RGB!)
lower_bound = np.array([105, 105, 105], dtype=np.uint8)
upper_bound = np.array([255, 255, 255], dtype=np.uint8)

# Create a mask where pixels in the range are white (255), others black (0)
mask = cv2.inRange(ROI, lower_bound, upper_bound)

# Choose your validation logic:
# Option 1: Check if ALL pixels in ROI are within the range
# all_valid = np.all(mask == 255)

# Option 2: Check if MOST pixels (e.g., >50%) are within the range (more practical for real images)
total_pixels = ROI.shape[0] * ROI.shape[1]
valid_pixels = np.count_nonzero(mask)
valid_ratio = valid_pixels / total_pixels
is_valid = valid_ratio > 0.5  # Adjust this threshold based on your needs

# Set status and text color
if is_valid:
    status = 'left'
    text_color = (0, 255, 0)  # Green for valid status
else:
    status = 'write'
    text_color = (0, 0, 255)  # Red for invalid status

# Add text to the frame (removed unused alpha channel from color tuple)
cv2.putText(frame, f"Status {status}", (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 1, text_color, 3)

cv2.imshow('img', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()

Key Details to Know:

  • OpenCV Color Format: cv2.imread loads images in BGR order, so your gray-scale bounds (105,105,105) work perfectly here since all channels are equal.
  • Mask Usage: cv2.inRange is the standard tool for detecting pixels within a color range—it generates a binary mask to highlight valid pixels.
  • Flexible Validation:
    • Use the "all pixels valid" check if you need strict adherence to the color range.
    • Use the ratio check for real-world images, where minor noise or small color variations are common. Adjust the 0.5 threshold to make the check more or less strict.
  • Text Rendering: The alpha channel in your original color tuple wasn't necessary for standard OpenCV windows, so I removed it to avoid confusion.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:27:40