如果您愿意,可以使用嵌套循环来实现,但这会很慢而且很笨重。我建议使用 numpy 内置的优化方法
假设您的图像是一个二维numpy 数组,黑色值为0,白色值为255,如下所示:
image = np.random.choice([0,255], size=(10,10), p=[0.8, 0.2])
>>> image
array([[ 0, 0, 255, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 255, 0],
[ 0, 0, 0, 255, 0, 0, 0, 0, 0, 0],
[ 0, 255, 0, 255, 255, 0, 0, 0, 255, 255],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[255, 0, 0, 0, 255, 0, 0, 0, 0, 0],
[ 0, 255, 255, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[255, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[255, 255, 0, 0, 255, 255, 255, 255, 0, 255]])
您可以像这样找到白色值(值等于 255)的第一个和最后一个坐标:
white_pixels = np.array(np.where(image == 255))
first_white_pixel = white_pixels[:,0]
last_white_pixel = white_pixels[:,-1]
导致:
>>> first_white_pixel
array([0, 2])
>>> last_white_pixel
array([9, 9])
或者,作为一个班轮:
first_white_pixel, last_white_pixel = np.array(np.where(image == 255))[:,[0,-1]].T