【问题标题】:How to modify a function that works on RGB images to make it work for a monochrome image?如何修改适用于 RGB 图像的函数以使其适用于单色图像?
【发布时间】:2021-10-10 06:37:30
【问题描述】:

以下代码适用于 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

【问题讨论】:

  • 作为一个非常快速、简单且内存效率极低且无需思考的第一次 stab,您可以使用 np.dstack((grey,grey,grey)) 传递灰度图像的 RGB 版本
  • 我认为这是唯一可能的方法。如果您回答我的问题,我可以接受它作为答案。它至少有效。
  • 让我们暂时搁置一下,我会在几天后将其作为答案 - StackOverflow 上有一些聪明的人可能会回答得更好,但可能会推迟回答如果他们认为我的想法回答了您的问题...

标签: python pandas image dataframe image-processing


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-01-09
    • 2012-07-28
    • 1970-01-01
    • 2018-01-14
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多