首页 > 解决方案 > 如何修改适用于 RGB 图像的函数以使其适用于单色图像?

问题描述

下面的代码适用于 RGB 图像(对于形状:512x512x3)。我需要做的是让它适用于单通道单色图像。(形状:512x512)我应该修改哪些部分?

def get_triangle_colour(triangles, image, agg_func=np.median):
    """
    Get's the colour of a triangle, based on applying agg_func to the pixels
    under it
    :param triangles: scipy.spatial.Delaunay
    :param image: image as array
    :param agg_func: function
    :return: colour list
    """
    # create a list of all pixel coordinates
    ymax, xmax = image.shape[:2]
    xx, yy = np.meshgrid(np.arange(xmax), np.arange(ymax))
    pixel_coords = np.c_[xx.ravel(), yy.ravel()]

    # for each pixel, identify which triangle it belongs to
    triangles_for_coord = triangles.find_simplex(pixel_coords)

    df = pd.DataFrame({
        "triangle": triangles_for_coord,
        "r": image.reshape(-1, 3)[:, 0],
        "g": image.reshape(-1, 3)[:, 1],
        "b": image.reshape(-1, 3)[:, 2]
    })
    
    #find the median color of the triangle
    by_triangle = (
        df
            .groupby("triangle")
        [["r", "g", "b"]]
            .aggregate(agg_func)
            .reindex(range(n_triangles), fill_value=0)
        # some triangles might not have pixels in them
    )

    return by_triangle.values / 256

标签: pythonpandasimagedataframeimage-processing

解决方案


作为一个非常快速、简单且内存效率极低且无需思考的第一次插入,您可以通过以下方式传递灰度图像的 RGB 版本(其中 R=G=B):

np.dstack((grey,grey,grey))       # or save a few keystrokes with np.dstack([grey]*3)

推荐阅读