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

如何使用OpenCV检测指定x,y坐标周边区域内的白像素

OpenCV白像素区域检测实现方案

问题先给明确结论:

  • 不需要重复手动选择裁剪图的坐标,目标位置固定的场景直接写死相对坐标即可
  • 完全支持同时检测多个不同坐标的区域,用列表循环处理即可
  • 更简便的实现可以省掉二次读取裁剪图的IO步骤,直接用内存中已生成的crop变量处理,效率更高

具体实现代码

直接替换原有代码中「检测白像素」部分的逻辑即可,完整可运行的修改版如下:

import numpy as np
import cv2

img = cv2.imread('Image.jpg')
#img = cv2.imread('Image2.jpg') 
#img = cv2.imread('Image3.jpg')

mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)

rect = (1512, 20, 180, 185) # 感兴趣区域边界
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:, :, np.newaxis]
cv2.imwrite('Image_mask.jpg', img)

# 指定固定位置的x,y坐标
mx = (1510, 22, 110, 185)
x, y, h, w = mx

# 输出文件
crop = img[y:y+h, x:x+w]
cv2.imwrite('Image_crop.jpg', crop)

cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imwrite('Image_cont.jpg', img)

# 检测裁剪图中的白像素,省去二次读文件步骤,直接用crop变量处理
gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
ret, gray = cv2.threshold(gray, 150, 255, 0)

# 配置要检测的20x20区域,格式:(区域左上角x坐标, 区域左上角y坐标, 区域宽度, 区域高度)
# 多个区域直接往列表里加元素即可,这里示例配置2个检测区域
detect_areas = [
    (10, 10, 20, 20), # 第一个检测区域,坐标为相对于裁剪图的坐标
    (50, 50, 20, 20)  # 第二个检测区域
]

# 遍历所有区域检测
for idx, (area_x, area_y, area_w, area_h) in enumerate(detect_areas):
    # 切片取对应区域
    area_gray = gray[area_y:area_y+area_h, area_x:area_x+area_w]
    # 统计白像素(值为255)的数量
    white_pixel_count = np.sum(area_gray == 255)
    if white_pixel_count > 0:
        print(f"第{idx+1}个检测区域内存在白像素,数量为:{white_pixel_count}")
    else:
        print(f"第{idx+1}个检测区域内不存在白像素")

# 可视化展示
cv2.imshow('Threshold Result', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

可选优化方案

如果你的目标物体位置不固定,不想手动配置检测区域坐标,可以先在阈值化后的灰度图上做轮廓检测,找到目标物体的最小外接矩形,再向外偏移指定像素生成周边的检测区域,全程自动化不需要手动配坐标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:39:00