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

Python 3.9中特定X轴位置黑色区域的定位方法咨询

检测图像特定X轴位置的黑色区域并提取位置(Python 3.9)

基于你已有的图像加载代码,我们可以扩展实现特定X轴位置的黑色区域检测,具体实现如下:

核心逻辑

选定目标X坐标后,提取该列的所有像素,判断哪些像素属于黑色(兼容RGB/RGBA/灰度图像),最后整理出黑色区域的Y坐标或连续区间。

完整代码实现

from PIL import Image
import numpy as np

# 加载图像并转为numpy数组
im = Image.open('c97dae05fd9244d4d10305b8066246psXmnlRxU59D0kJ0-0.jpeg')
imarray = np.array(im)

# 指定要检测的X轴位置(按需修改)
target_x = 50

# 判断像素是否为黑色的函数,tolerance可兼容非纯黑的噪点
def is_black(pixel, tolerance=0):
    # 处理RGB/RGBA图像,忽略alpha通道
    if len(pixel) >= 3:
        rgb = pixel[:3]
        return all(channel <= tolerance for channel in rgb)
    # 处理灰度图像
    else:
        return pixel <= tolerance

# 提取目标X列的所有像素
column_pixels = imarray[:, target_x, :] if len(imarray.shape) == 3 else imarray[:, target_x]

# 收集所有黑色像素的Y坐标
black_y_positions = [y for y, pixel in enumerate(column_pixels) if is_black(pixel)]

# 把连续的Y坐标合并成区间(更直观展示黑色区域范围)
if black_y_positions:
    black_regions = []
    start = black_y_positions[0]
    end = start
    for y in black_y_positions[1:]:
        if y == end + 1:
            end = y
        else:
            black_regions.append((start, end))
            start = y
            end = y
    black_regions.append((start, end))
    
    print(f"X={target_x}位置的黑色区域:")
    for i, (s, e) in enumerate(black_regions):
        print(f"区域{i+1}: Y从{s}到{e}")
else:
    print(f"X={target_x}位置没找到黑色区域")

关键细节说明

  • 阈值调整:如果图像里的黑色不是纯黑(比如带轻微噪点),可以把tolerance设为10或其他值,允许像素值在0到阈值之间都被判定为黑色。
  • 图像模式兼容:代码自动识别RGB/RGBA/灰度图像,无需额外转换格式。
  • 结果灵活使用:如果不需要连续区间,直接用black_y_positions列表就能拿到所有黑色像素的单个Y坐标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:05:23