Python3 Pillow 获取一条线上的所有像素

5 投票
4 回答
7192 浏览
提问于 2025-04-18 12:58

我需要获取一条线上的像素值,我正在使用Python3和Pillow。在opencv中,有一个叫做LineIterator的东西,可以返回两个点之间的所有相关像素,但我在Pillow的文档中没有找到类似的东西。

我使用Pillow是因为我最开始看到这个帖子,里面说Python3没有opencv的支持。我知道这个帖子是2012年的,但这个帖子似乎是今年的,虽然帖子上没有年份。可是当我运行pip3.2 search opencv时,我能看到一个叫pyopencv的东西,但我无法安装它,系统提示找不到合适的版本(可能是python2.x和python3.x之间的问题)。

我希望的解决方案按优先级排序如下:

  1. 一个正确安装opencv for python3的方法(最好是opencv 2.4.8)
  2. 仅使用Pillow获取线上的像素的方法
  3. 不涉及额外库(numpy/scipy)的简单解决方案
  4. 其他所有方案

4 个回答

2

对于需要现成解决方案的读者,这里有一个在scikit-image库中的方法:

skimage.measure.profile_line(image, start_point, end_point)
2

你可以试试opencv的开发版本3.0-dev。现在的2.4版本不支持python3,具体可以查看这个回答

在使用pillow的时候,Image.getpixel可以帮你获取像素值。所以,你可以用纯python简单地插值两个点,然后把这些索引传给Image.getpixel。我不知道有没有优雅的纯python实现来插值,获取一条线上的所有像素。

如果觉得这样太麻烦,你可以用numpy/matplotlib来更简单(懒惰)地完成这个任务。你可以使用matplotlib.path.Path来创建一个路径,并用它的contains_points方法来检查所有可能的点(比如可以用numpy.meshgrid获取这两个点定义的边界框内的所有像素坐标)。

5

我试了@Rick建议的代码,但没成功。然后我去看了Xiaolin写的Matlab代码,把它翻译成了Python:

def xiaoline(x0, y0, x1, y1):

        x=[]
        y=[]
        dx = x1-x0
        dy = y1-y0
        steep = abs(dx) < abs(dy)

        if steep:
            x0,y0 = y0,x0
            x1,y1 = y1,x1
            dy,dx = dx,dy

        if x0 > x1:
            x0,x1 = x1,x0
            y0,y1 = y1,y0

        gradient = float(dy) / float(dx)  # slope

        """ handle first endpoint """
        xend = round(x0)
        yend = y0 + gradient * (xend - x0)
        xpxl0 = int(xend)
        ypxl0 = int(yend)
        x.append(xpxl0)
        y.append(ypxl0) 
        x.append(xpxl0)
        y.append(ypxl0+1)
        intery = yend + gradient

        """ handles the second point """
        xend = round (x1);
        yend = y1 + gradient * (xend - x1);
        xpxl1 = int(xend)
        ypxl1 = int (yend)
        x.append(xpxl1)
        y.append(ypxl1) 
        x.append(xpxl1)
        y.append(ypxl1 + 1)

        """ main loop """
        for px in range(xpxl0 + 1 , xpxl1):
            x.append(px)
            y.append(int(intery))
            x.append(px)
            y.append(int(intery) + 1)
            intery = intery + gradient;

        if steep:
            y,x = x,y

        coords=zip(x,y)

        return coords

最后,我用上面的代码写了一个绘图的脚本:

    import numpy as np 
    import demo_interpolate_pixels_along_line as interp 
    import matplotlib.pyplot as plt


    A=np.zeros((21,21))

    p0=(5,15)
    p1=(20,5)

    coords=interp.xiaoline(p0[0],p0[1],p1[0],p1[1])
    for c in coords:
        A[c]=1

    A[p0]=0.2
    A[p1]=0.8

    plt.figure()
    plt.imshow(A.T,interpolation='none',
                    origin='lower',
                    cmap='gist_earth_r',
                    vmin=0,
                    vmax=1)
    plt.grid(which='major')
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.text(p0[0],p0[1],'0',fontsize=18,color='r')
    plt.text(p1[0],p1[1],'1',fontsize=18,color='r')
    plt.show()

...我没有足够的声望来发图片 :(

6

我最后选择了一个直接用Python实现的方案,这个方案是基于Xiaolin Wu的线段算法

def interpolate_pixels_along_line(x0, y0, x1, y1):
    """Uses Xiaolin Wu's line algorithm to interpolate all of the pixels along a
    straight line, given two points (x0, y0) and (x1, y1)

    Wikipedia article containing pseudo code that function was based off of:
        http://en.wikipedia.org/wiki/Xiaolin_Wu's_line_algorithm
    """
    pixels = []
    steep = abs(y1 - y0) > abs(x1 - x0)

    # Ensure that the path to be interpolated is shallow and from left to right
    if steep:
        t = x0
        x0 = y0
        y0 = t

        t = x1
        x1 = y1
        y1 = t

    if x0 > x1:
        t = x0
        x0 = x1
        x1 = t

        t = y0
        y0 = y1
        y1 = t

    dx = x1 - x0
    dy = y1 - y0
    gradient = dy / dx  # slope

    # Get the first given coordinate and add it to the return list
    x_end = round(x0)
    y_end = y0 + (gradient * (x_end - x0))
    xpxl0 = x_end
    ypxl0 = round(y_end)
    if steep:
        pixels.extend([(ypxl0, xpxl0), (ypxl0 + 1, xpxl0)])
    else:
        pixels.extend([(xpxl0, ypxl0), (xpxl0, ypxl0 + 1)])

    interpolated_y = y_end + gradient

    # Get the second given coordinate to give the main loop a range
    x_end = round(x1)
    y_end = y1 + (gradient * (x_end - x1))
    xpxl1 = x_end
    ypxl1 = round(y_end)

    # Loop between the first x coordinate and the second x coordinate, interpolating the y coordinates
    for x in range(xpxl0 + 1, xpxl1):
        if steep:
            pixels.extend([(math.floor(interpolated_y), x), (math.floor(interpolated_y) + 1, x)])

        else:
            pixels.extend([(x, math.floor(interpolated_y)), (x, math.floor(interpolated_y) + 1)])

        interpolated_y += gradient

    # Add the second given coordinate to the given list
    if steep:
        pixels.extend([(ypxl1, xpxl1), (ypxl1 + 1, xpxl1)])
    else:
        pixels.extend([(xpxl1, ypxl1), (xpxl1, ypxl1 + 1)])

    return pixels

撰写回答