如何修改适用于 RGB 图像的函数以使其适用于单色图像?
How to modify a function that works on RGB images to make it work for a monochrome image?
以下代码适用于 RGB 图像(形状:512x512x3)。我需要做的是让它适用于单通道单色图像。 (for shape: 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
作为不需要思考的真正快速、简单且内存效率极低的第一次尝试,您可以传递灰度图像的 RGB 版本(其中 R=G=B):
np.dstack((grey,grey,grey)) # or save a few keystrokes with np.dstack([grey]*3)
以下代码适用于 RGB 图像(形状:512x512x3)。我需要做的是让它适用于单通道单色图像。 (for shape: 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
作为不需要思考的真正快速、简单且内存效率极低的第一次尝试,您可以传递灰度图像的 RGB 版本(其中 R=G=B):
np.dstack((grey,grey,grey)) # or save a few keystrokes with np.dstack([grey]*3)