我们有 100x100 像素的图像。在此图像中,红线是一条路径。当我将此图像解析为像素颜色时,我以随机顺序获得红色像素(实际上,我从图像中从上到下逐行获取像素)。但我想要获得从 A 点到 B 点的路径的有序点列表。如何做到这一点。
该函数获取红色像素(Python语言):
def getRoad(imgPng) -> list:
img = Image.open(imgPng)
pix = img.load()
width, height = img.size
x = 0
y = 0
road = []
for y in range(BORDER_OFFSET, height-BORDER_OFFSET, STEP):
for x in range(BORDER_OFFSET, width-BORDER_OFFSET, STEP):
color = pix[x, y]
if (COLOR_ROAD[0]-7 <= color[0] <= COLOR_ROAD[0]+7 and
COLOR_ROAD[1]-7 <= color[1] <= COLOR_ROAD[1]+7 and
COLOR_ROAD[2]-7 <= color[2] <= COLOR_ROAD[2]+7):
road.append((x, y))
# print(len(road))
return road
您可以通过首先收集所有红色像素,然后根据它们彼此的接近程度对它们进行排序,来提取图像中的红色路径并对其进行排序。下面的代码演示了如何在 Python 中使用
PIL
图像处理库和简单的基于距离的排序算法来实现此目的。
from PIL import Image
import math
def get_road(imgPng):
img = Image.open(imgPng)
pix = img.load()
width, height = img.size
road = []
for y in range(height):
for x in range(width):
color = pix[x, y]
if (230 <= color[0] <= 255 and 0 <= color[1] <= 50 and 0 <= color[2] <= 50):
road.append((x, y))
return road
def distance(point1, point2):
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def order_points(points, max_jump=50):
ordered = [points.pop(0)]
while points:
last = ordered[-1]
next_point = min(points, key=lambda point: distance(last, point))
if distance(last, next_point) > max_jump:
break
points.remove(next_point)
ordered.append(next_point)
return ordered
road_points = get_road('./image.png')
ordered_road_points = order_points(road_points)
print(ordered_road_points)