我需要在Python中编写一个循环,遍历图像中的所有像素。我需要找到所有白色像素并保存第一个检测到的像素和最后一个像素的坐标。该图像是阈值化的图像(仅具有黑白像素)。我已经写了一个嵌套循环,但不知道如何进行评估。
我需要在Python中编写一个循环,遍历图像中的所有像素。我需要找到所有白色像素并保存第一个检测到的像素和最后一个像素的坐标。该图像是阈值化的图像(仅具有黑白像素)。我已经写了一个嵌套循环,但不知道如何进行评估。
如果你愿意,你可以使用嵌套循环来完成这件事,但那样会很慢且不够优雅。我建议使用内置于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]])
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